CSS布局(二) 常见布局

本文是根据网上资料总结出来的文章

CSS 布局方式

一列布局

多用于显示标题展示等;

<div class="main"></div>

.main{
    width: 200px;
    height: 100px;
    background-color: green;
    margin: 0 auto;
}

两列布局

两列布局,最常见的就是使用float来实现。float浮动布局的缺点是浮动后会造成文本环绕等效果,以及需要及时清除浮动。

注意:
1.如何父级元素没有设置高度,则需要设置overflow:hidden来清除浮动产生的影响
2.对于自己相邻元素清除浮动产生的影响用:clear:both;

<div class="main">
  <div class="left">left</div>
  <div class="right">right</div>
</div>

.main {
  width: 400px;
  background: red;
  overflow: hidden;
}

.left {
  background: yellow;
  float: left;
}

.right {
  background: green;
  float: left;
}

三列布局

两侧定宽中间自适应,首先设置父级元素的宽度,可以左左右设置浮动。然后中间设置margin调整间距。 也可以都设置成左浮动,设置margin,调整间距。同样注意清除浮动的影响!

<div class="main">
  <div class="left">left</div>
  <div class="middle">middle</div>
  <div class="right">right</div>
</div>

.main {
  width: 100%;
  background: red;
  overflow: hidden;
}

.left {
  background: yellow;
  float: left;
  width: 100px;
}

.middle {
  background: rosybrown;
  float: left;
  width: calc(100% - 200px);
}

.right {
  background: green;
  float: right;
  width: 100px;
}

或着为父级元素设置relative属性,再为子元素设置absolute属性,再分别定位,调间距。

<div class="parent" style="background-color: lightgrey;">
    <div class="left" style="background-color: lightblue;">
        <p>left</p>
    </div>    
    <div class="center" style="background-color: pink;">
        <p>center</p>
        <p>center</p>
    </div>                
    <div class="right"  style="background-color: lightgreen;">
        <p>right</p>
    </div>            
</div>


p{margin: 0;}
.parent{position: relative;height:40px;}
.left,.right,.center{position: absolute;}
.left{left: 0;width:100px;}
.right{right: 0;width: 100px;}
.center{left: 120px; right: 120px;}

混合布局

在一列布局的基础上,保留top和foot部分,将中间的main部分改造成两列或三列布局,小的模块可以再逐级同理划分。

<div class="top"></div>
<div class="main">
  <div class="left">left</div>
  <div class="right">right</div>
</div>
<div class="footer"></div>

.top{
            height: 100px;
            background: teal;
        }
        .footer{
            height: 100px;
            background: wheat;
        }
        .main{
            width: 100%;
            background: red;
            overflow: hidden;
        }
        .left{
            background: yellow;
            float: left;
            width: 50%;
        }
        .right{
            background: green;
            float: right;
            width: 50%;
        }

等分布局

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>

 body {
      margin: 0;
    }

    .parent {
      border: 1px solid red;
      overflow: hidden;
      margin-right: -10px;
    }

    .child {
      width: calc(25% - 10px);
      height: 100px;
      background: green;
      float: left;
      margin-right: 10px;
    }

猜你喜欢

转载自www.cnblogs.com/jadedoo/p/10201025.html