正常页面布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<style> *{ margin:0; padding: 0; } .content{ width:400px; border:1px solid #000;
} .box{ width:200px; height:200px; background: greenyellow;
} </style>
<body> <div class="content"> <div class="box"></div> </div> <p>基苦阿斯蒂芬</p> </body> |
当给类名为.box的盒子加上浮动后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<style> *{ margin:0; padding: 0; } .content{ width:400px; border:1px solid #000;
} .box{ width:200px; height:200px; background: greenyellow; float: left;
} </style> |
可以看到页面布局已经乱了,因为元素设置浮动后会脱离文档流
1 利用BFC(给父元素加上overflow:hidden)
**缺点:父元素溢出的元素会隐藏,可能会影响页面显示 **
1 2 3 4 5 6 |
.content{ width:400px; border:1px solid #000; overflow: hidden;
} |
2 加空div
要点:
1.加上一个空的块级元素
2.对块级元素进行清除浮动, 省事方法,不管理是左浮还是右浮,直接全清(clear:both)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<style> *{ margin:0; padding: 0; } .content{ width:400px; border:1px solid #000; /* overflow: hidden; */
} .box{ width:200px; height:200px; background: greenyellow; float: left;
} .clear{ clear: both; } </style>
<body> <div class="content"> <div class="box"></div> <div class="clear"></div> </div> <p>基苦阿斯蒂芬</p> </body> |
3 利用伪元素
要点:
1 其实和加空div的原理是一致的,唯一要记住的就是把伪元素转为块级元素(display:block),否则会没有效果
2 还有伪元素的属性不要忘记加上(content:‘’)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<style> *{ margin:0; padding: 0; } .content{ width:400px; border:1px solid #000; /* overflow: hidden; */
} .content::after{ content: ''; display: block; // 必须要转换为块元素 clear: both; } .box{ width:200px; height:200px; background: greenyellow; float: left;
} /* .clear{ clear: both; } */ </style>
<body> <div class="content"> <div class="box"></div> <!-- <div class="clear"></div> --> </div> <p>基苦阿斯蒂芬</p> </body> |