overflow:hidden的作用
overflow:hidden的作用
一:清除浮动
- 
这里有四个盒子,一个father,两个son。我们设置如下样式: /* CSS */ <div class="father"> <div class="son1">son1</div> <div class="son2">son2</div> </div> /* HTML */ <style> .father { /* 父亲没有设置高度 */ width: 500px; background-color: pink; } .son1 { /* 儿子没有浮动 */ width: 100px; height: 100px; background-color: aquamarine; } .son2 { width: 100px; height: 100px; background-color: rgb(99, 77, 177); } .brother { width: 400px; height: 300px; background-color: skyblue; } </style> 当我们给子级添加float:left 时,子级脱离标准流,父级宽度变为0。就会发现浮动的盒子将其压在下面,造成页面塌陷: .son1, .son2 { float:left; } 因此,需要给父级加个overflow:hidden属性,这样父级的高度就随子级容器及子级内容的高度而自适应。 .father { overflow:hidden; } 
二:外边距塌陷
 父级元素内有子元素,如果给子元素添加margin-top的样式,那么父级元素也会跟着下来,造成外边距塌陷,如图:
/* CSS */
.father {
    width: 500px;
    background-color: pink;
}
.son1 {
    margin-top: 50px;
    width: 100px;
    height: 100px;
    background-color: aquamarine;
}
/* HTML */
<div class="father">
    <div class="son1">son</div>
</div>

 这时,给父级元素添加overflow:hidden,就可以解决这个问题。
.father {
	overflow:hidden;
}

三:溢出隐藏
 若给父元素添加overflow:hidden,则子元素超出部分会被隐藏。例如:
/* CSS */
div {
    width: 120px;
    white-space: nowrap; /* 超出不换行 */
    background-color: pink;
}
/* HTML */
<div>
    今天是2022/1/6,王韩六六在博客园写随笔。。。
</div>

给父元素添加overflow:hidden后,

注:一般情况,隐藏部分会显示省略号。
div {
    overflow: hidden;
    width: 120px;
    white-space: nowrap;
    background-color: pink;
    text-overflow: ellipsis; /* 溢出部分显示省略号 */
}

以上,就是overflow:hidden的作用:清除浮动、外边距塌陷、溢出隐藏。
作者:王韩六六
        
        本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  
     
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号