Skip to content

08 浮动布局的问题和清除浮动

  • 如何实现圣杯布局和双飞翼布局
  • 手写 clearfix

圣杯布局和双飞翼布局的目的

  • 三栏布局,中间一栏最先加载和渲染(内容最重要)
  • 两侧内容固定,中间内容随着宽度自适应
  • 一般用于 PC 网页

圣杯布局和双飞翼布局的技术总结

  • 使用 float 布局
  • 两侧使用 margin 负值,以便和中间内容横向重叠
  • 防止中间内容被两侧覆盖,一个用 padding,一个用 margin

圣杯布局

查看代码
html
<div id="header">this is header</div>
<div id="container" class="clearfix">
  <div id="center" class="column">this is center</div>
  <div id="left" class="column">this is left</div>
  <div id="right" class="column">this is right</div>
</div>
<div id="footer">this is footer</div>

`

css
body {
  min-width: 550px;
}
#header {
  text-align: center;
  background-color: #f1f1f1;
}

/* #container {
    padding-left: 200px;
    padding-right: 150px;
  }

  #container .column {
    float: left;
  } */

#center {
  background-color: #ccc;
  width: 100%;
}

#left {
  background-color: yellow;
  width: 200px;
  /* position: relative;
    margin-left: -100%;
    right: 200px; */
}

#right {
  background-color: red;
  width: 150px;
  /* margin-right: -150px; */
}

#footer {
  /* clear: both; */
  text-align: center;
  background-color: #f1f1f1;
}

/* 手写 clearfix */
/* .clearfix:after {
    content: "";
    display: table;
    clear: both;
  } */

双飞翼布局

查看代码
html
<div id="main" class="col">
  <div id="main-wrap">this is main</div>
</div>
<div id="left" class="col">this is left</div>
<div id="right" class="col">this is right</div>
css
body {
  min-width: 550px;
}

/* .col {
    float: left;
  } */

#main {
  width: 100%;
  height: 200px;
  background-color: #ccc;
}

/* #main-wrap {
    margin: 0 190px 0 190px;
  } */

#left {
  width: 190px;
  height: 200px;
  background-color: #0000ff;
  /*   margin-left: -100%; */
}

#right {
  width: 190px;
  height: 200px;
  background-color: #ff0000;
  /*   margin-left: -190px; */
}

清除浮动的方法

  • 添加空标签 clear:both
  • 父级 div 定义 height
  • 结尾处加空 div 标签 clear:both
  • 父级 div 定义伪类 :after 和 zoom
查看代码
html
<div class="clearfix">
  <div style="float: left;">浮动元素 1</div>
  <div style="float: left;">浮动元素 2</div>
</div>
css
.clearfix:after {
  content: '';
  display: table; /* 使伪元素生成一个块级元素,它会参与布局计算。*/
  clear: both; /* 确保浮动元素不影响伪元素。*/
}

/* 为了确保 IE6/7 的兼容性 */
.clearfix {
  *zoom: 1; /* 触发 hasLayout,在 IE6/7 中强制父元素包含浮动元素。 */
}