浮动元素脱离文档流
使用float脱离文档流时,其余盒子会无视这个元素,但其余盒子内的文本仍然会为这个元素让出位置,环绕在该元素的附近。
<pre style="margin: 0px; padding: 0px; overflow: auto; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;"><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><style>.first {width: 200px; height: 200px; border: 3px solid red;float: left;} .second { width: 200px;height: 100px; border: 3px solid blue;}</style></head><body><div class="first">123</div><div class="second">456</div></body></html></pre>外部距塌陷问题
1,当上下相邻的两个块级元素相遇,上面的元素有下边距margin-bottom,下面的元素有上边距margin-top,则它们之间的垂直距离取两个值中的较大者。
<style>.box1 {width: 150px;height: 100px;margin-bottom: 20px;background-color: rgb(201, 239, 98);}.box2 {width: 100px;height: 100px;background-color: rebeccapurple;margin-top: 10px;}</style><div class="box1"></div><div class="box2"></div>这时候两个盒子之间的垂直距离不是30px,而是20px。
处理方法:
尽量只给一个盒子增加margin值。
2.对于两个嵌套关系的块元素,假如父元素没有上内边距及边框,父元素的上外边距会与子元素的上外边距发生合并,合并后的外边距为两者中的较大者。
<style>.box1 {width: 150px;height: 100px;margin-top: 20px; /* border: 1px solid #000000; */background-color: red;}.box2 {width: 100px;height: 100px;/* border: 1px solid #000000; */background-color: rebeccapurple;margin-top: 10px;}</style></head> <body><div class="box1"><div class="box2"></div></div></body>这时候两个盒子会发生合并,上外边距为20px。
处理办法:
①给父元素定义上边框
②给父元素定义上内边距
③给父元素增加 overflow:hidden;
④增加浮动
⑤增加绝对定位
3.假如存在一个空的块级元素,border、padding、inline content、height、min-height都不存在,那么上下边距中间将没有任何阻隔,上下外边距将会合并。
<p style="margin-bottom: 0px;">这个段落的和下面段落的距离将为20px</p><div style="margin-top: 20px; margin-bottom: 20px;"></div><p style="margin-top: 0px;">这个段落的和上面段落的距离将为20px</p>可以了解成中间div宽度为0且上下边距融合,只取margin的最大值。
清理浮动的方式
1,使用额外标签法:
在浮动的盒子之下再放一个标签,在这个标签中使用clear:both,来清理浮动对页面的影响。
.clearfix{ clear: both; }<div class="clearfix"></div>a.内部标签:会将这个浮动盒子的父盒子高度重新撑开
b.外部标签:会将这个浮动盒子的影响清理,但是不会撑开父盒子。
注意:一般情况下不会使用这一种方式来清理浮动。由于这种清理浮动的方式会添加页面的标签。
2,使用overflow属性来清理浮动:
先找到浮动盒子的父元素,再在父元素中增加一个属性,就是清理这个父元素中的子元素浮动对页面的影响。
overflow: hidden;3,使用伪元从来清理浮动:
.clearfix:after {content: "";//增加内容为空height: 0;//内容高度为0line-height: 0;//内容文本的高度为0display: block;//将文本设置为块级元素clear: both;//清理浮动visibility: hidden;//将元素隐藏}.clearfix {zoom: 1;/*为了兼容ie6*/}