前端路上遇见的奇怪问题--魔幻的float?

278 阅读2分钟
.parent 
{ background-color: red;/* border: blue solid 1px; */}
.son
{width: 100px;height: 100px;background-color: silver;}
.box1
{  height: 200px;  width: 200px;  background-color: pink;}

css代码如上 页面结构如下

 <div class="parent ">
    <div class="son">儿子</div>
 </div>
 <div class="box1"> </div>

显示效果如下 可以理解:

此时给son添加float:left,父元素高度丢失,导致son和box1重叠 这也能理解

此时在给选择器box1 clear:left; 此时呢son和box1就不会重叠效果图如下

接下来就有些奇怪了 注释掉clear: left,给box1 添加一个上外边距 页面结构不变显示效果就是如下和我想象中的不一样。想象中的应该是son不动 box1下移150px;

.parent 
{ background-color: red; /* border: blue solid 1px; */ }
.son
{width: 100px;height: 100px;background-color: silver;float: left;            }
.box1
{height: 200px;width: 200px;background-color: pink; /* clear: left; */
 margin-top: 150px;}

**儿子为什么也下移了呢??**原因是什么呢?不知道!parent元素没有了高度,那么给父元素一个border此时的显示效果就是如下:

既然想到了是父亲没有了高度,那么给父亲一个height:100px;

这就正常了。修改一下css代码

.parent{ 
    background-color: red;
    /* border: blue solid 1px; */
    /* height: 100px; */
}
.son{
    width: 100px;
    height: 100px;
    background-color: silver;float: left;
      }
.box1{
height: 200px;
width: 200px;
background-color: pink;
/* clear: left; */
 margin-top: 150px;}
.clearfix::before{
display: table;content: '';
 /* clear: both; */}

  <div class="parent clearfix"> 
           <div class="son">儿子</div>
    </div>    
<div class="box1">box1</div>

总结一下:默认情况下 ,父元素的高度由子元素的内容撑开,当使用float属性后,son脱离了文档流,父元素高度丢失,此时给box1添加一个上外边距无法使得只有box1下移150px;实际上是son和box1都会下移,经过上面的测试发现只要给parent高度撑开,margin-top就会起效果,除此之外在box1前面加一个

111
也会起效,完全不需要写clearfix这个类选择器。如下图所示。 

.parent 
{ background-color: red;   
/* border: blue solid 1px; */ 
/* height: 100px; */
 } 
.son{  
width: 100px; 
height: 100px;
background-color: silver; 
float: left;
   }        
.box1{
 height: 200px;
width: 200px;
background-color: pink; 
/* clear: left; */
margin-top: 150px;
}



<body>
<div>111</div><div class="parent"> 
  <div class="son">儿子</div><
/div
><div class="box1">box1</div>
</body>

至于为什么,个人表示目前不清楚。。。只能说因吹斯听!!