浮动布局

67 阅读2分钟

浮动样式

float: left 左浮动

float: right 右浮动

  • 不支持text-align
  • 不识别回车
  • 右浮动的展示顺序
<div id="app">
  <div class="box">
    <div class='one'>1</div>
    <div class='two'>2</div>
    <div class='three'>3</div>
    <div class='four'>4</div>
  </div>
</div>

.box{
  width: 700px;
  height: 300px;
  background-color: darkkhaki;
}
.box div{
  width: 100px;
  height: 100px;
  float: right;
  text-align: center;
  line-height: 100px;
}
.one{
  background-color: blueviolet;
}
.two{
  background-color: darkorange;
}
.three{
  background-color: dodgerblue;
}
.four{
  background-color: forestgreen;
}

效果图:

image.png

  • 若n个元素都设置浮动,则横向排列
  • 设置浮动的元素都会脱离网页文档,与其他元素发生重叠,但不会有文字发生重叠,文字内容是环绕浮动元素的。

image.png

  • 浮动元素在排列时,只考虑前一个元素的位置
.box{
  width: 260px;
  height: 300px;
  background-color: darkkhaki;
}
.box div{
  float: left;
  text-align: center;
}
.one{
  width: 100px;
  height: 100px;
  line-height: 100px;
  background-color: blueviolet;
}
.two{
  width: 50px;
  height: 50px;
  line-height: 50px;
  background-color: darkorange;
}
.three{
  width: 100px;
  height: 30px;
  line-height: 30px;
  background-color: dodgerblue;
}
.four{
  width: 100px;
  height: 100px;
  line-height: 100px;
  background-color: forestgreen;
}

效果图:(改变宽度后得出结论:4元素在排列时只考虑3元素)

image.png

image.png

清除浮动

clear: left/right/both 表示清除浮动(不受到左/右/全部浮动的影响)

  • 不希望谁受到浮动的影响就给谁增加清除浮动样式
.box{
  width: 260px;
  height: 300px;
  background-color: darkkhaki;
}
.box div{
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
}
.one{
  float: left;
  background-color: blueviolet;
}
.two{
  float: right;
  clear: left/both;
  background-color: darkorange;
}
.three{
  float: left;
  clear: right/both;
  background-color: dodgerblue;
}
.four{
  float: right;
  clear: left/both;
  background-color: forestgreen;
}

效果图:

image.png

加入clear样式变为:

image.png

解决高度塌陷

高度塌陷指:子盒子浮动,父盒子高度为0不能撑开的现象

  • 给父元素设置与浮动元素等高的高度
  • 给父盒子加overflow: hidden可以自适应内容高度(不设置高度)
    • overflow: hidden表示对于超出边界的元素,父元素可以做出相应调整
  • 在所有浮动盒子的下面添加一个空盒子,并设置clear: both,高度可设置为0
  • 给父盒子添加伪元素(万能
.box::after{
  content: ' ';
  clear: both;
  display: block;
  visibility: hidden;//隐藏站位
}