overflow:hidden不会隐藏所有子元素

发布时间 2023-07-03 18:22:29作者: 泠风lj

overflow:hidden不会被隐藏的情况

拥有overflow:hidden样式的块元素内部的元素溢出有时候不会被隐藏。当同时满足以下条件:

拥有overflow:hidden样式的块元素不具有position:relative和position:absolute样式;
内部溢出的元素是通过position:absolute绝对定位,并且该定位元素的包含块是设置overflow:hidden元素的父级元素。

 

CSS2.1对overflow的描述

可以参考CSS2.1规范对overflow的描述:

This property specifies whether content of a block container element is clipped when it overflows the element’s box. It affects the clipping of all of the element’s content except any descendant elements (and their respective content and descendants) whose containing block is the viewport or an ancestor of the element。

大概意思是:overflow属性用于规定,当一个块元素容器的内容溢出元素的盒模型边界时是否对其进行剪裁。overflow属性影响被应用元素的所有内容的剪裁。但如果后代元素的包含块是整个视区(通常指浏览器内容可视区域,可以理解为body元素)或者是该容器(定义了overflow的元素)的父级元素时,则不受影响。

也就是说会被overflow:hidden隐藏的情况是:后代元素是绝对定位,但包含块是该容器(定义了overflow的元素);或者后代元素是非绝对定位元素。

 

overflow:hidden不会被隐藏的案例

如下代码所示,第一个盒子和第二个盒子都是绝对定位。但是第一个盒子的包含块是设置overflow:hidden元素的子元素,第二个盒子的包含块是视口。因此第一个盒子溢出隐藏,第二个盒子溢出可见。

<style>
.over-hidden{overflow:hidden; height:30px; font-size:14px; width:100px; border:2px dotted #ddd;}
.outer{position:relative}
.inner1{position:absolute; top:0; background:yellow;}
.inner2{position:absolute; top:70px; background:pink;}
</style>
<div class='over-hidden'>
    <div class='outer'>
        <div class='inner1'>这是第一个盒子。这是第一个盒子</div>
    </div>
    <div class='inner2'>这是第二个盒子。这是第二个盒子</div>
</div>

效果