常用布局

Author Avatar
Nico Zhang 2月 05, 2018
  • 在其它设备中阅读本文章

float布局

适用最广,支持IE5

  1. 儿子全加 float: left (right)
  2. 老子加 .clearfix清除浮动
.clearfix:after{
    content: '';
    display: block;
    clear: both;
}

/* 兼容IE6,加上下面 */
.clearfix{
    zoom: 1;
}

子级元素浮动起来后,父容器不能自适应高度包容浮动的元素,所以需要清理浮动来达到包容浮动元素的目的

float平均布局

如果宽度不够,负 margin

例子

flex布局

博客

BFC

  1. 用 BFC 包住浮动元素。
  2. 用 float + div 做左右自适应布局
  3. MDN对BFC的描述

垂直居中

  1. absolute + margin auto
  <div class="parent">
    <div class="child">
    文字文字
    </div>
  </div>
.parent{
  height: 600px;
  border: 1px solid red;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  width: 300px;
  height: 200px;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
  1. flex居中
 <div class="parent">
    <div class="child">
     文字文字
    </div>
  </div>
   .parent{
  height: 600px;
  border: 3px solid red;

  display: flex;
  justify-content: center;
  align-items: center;
}
.child{
  border: 3px solid green;
  width: 300px;
}
  1. absolute+负margin
 <div class="parent">
    <div class="child">
      文字文字
    </div>
  </div>
.parent{
  height: 600px;
  border: 1px solid red;
  position: relative;
}
.child{
  border: 1px solid green;
  width: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -150px;
  height: 100px;
  margin-top: -50px;
}
  1. absolute + translate
 <div class="parent">
    <div class="child">
      文字文字
    </div>
  </div>
.parent{
  height: 600px;
  border: 1px solid red;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
  1. 伪元素 + inline-block
<div class="parent">
    <div class="child">
      文字文字
    </div>
  </div>
.parent{
  border: 3px solid red;
  height: 600px;
  text-align: center;
}

.child{
  border: 3px solid black;
  display: inline-block;
  width: 300px;
  vertical-align: middle;
}

.parent:before{
  content:'';
  outline: 3px solid red;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.parent:after{
  content:'';
  outline: 3px solid red;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
  1. div+table属性
<div class="table">
      <div class="td">
        <div class="child">
          文字文字
        </div>
    </div>
  </div>
div.table{
  display: table;
  border: 1px solid red;
  height: 600px;
}

div.tr{
  display: table-row;
  border: 1px solid green;
}

div.td{
  display: table-cell;
  border: 1px solid blue;
  vertical-align: middle;
}
.child{
  border: 10px solid black;
}