在我们平时写代码时会不会出现一个这样的问题,父层有设置overflow: hidden、内部元素有设置position: absolute然而却没有预期的脱离文档流显示出来,还是被溢出隐藏了,特别是在引入第三方插件时,让我深思是什么reason?
比如我们看如下代码
.container {
width: 50%;
height: 500px;
margin: 100px auto;
background-color: orange;
overflow: hidden;
position: relative;
}
.tips {
color: blueviolet;
width: calc(100% + 100px);
position: absolute;
top: 0;
left: 0;
}
<div class="container">
<div class="tips">
我需要超出隐藏1,我需要超出隐藏2,我需要超出隐藏3,我需要超出隐藏4,我需要超出隐藏5,我需要超出隐藏6,我需要超出隐藏7,我需要超出隐藏8,我需要超出隐藏9,我需要超出隐藏10。
</div>
</div>
附图
此时的结果是否和你预期的一样呢!
如图所示,我们内部元素并没有全部显示,因为我们的父元素上有一个position: relative属性,他并不会脱离文档,而是占据我们原来的空间,而我们的tips子元素相对于container元素定位,此时我们的tips还在overflow: hidden的可控范围容器内。
接下来,我们再进行改造一下
.container {
width: 50%;
height: 100px;
margin: 100px auto;
background-color: orange;
overflow: hidden;
}
.tips {
color: blueviolet;
width: calc(100% + 100px);
line-height: 20px;
position: absolute;
top: 0;
left: 0;
}
.relative {
position: relative;
}
.absolute {
position: absolute;
width: inherit;
}
<div class="container">
<div class="absolute">
<div class="relative">
<div class="tips">
我需要超出隐藏1,我需要超出隐藏2,我需要超出隐藏3,我需要超出隐藏4,我需要超出隐藏5,我需要超出隐藏6,我需要超出隐藏7,我需要超出隐藏8,我需要超出隐藏9,我需要超出隐藏10。
</div>
</div>
</div>
</div>
此时再看,没错,我们利用在外层重新嵌套一层position: absolute使其整体脱离文档,从而逃离了overflow: hidden
使用场景
在我们写代码时,可能会在一个盒子中会使用overflow: hidden解决margin坍塌问题,鼠标经过那个盒子某个地方显示浮层
那我们再改造一下
.container {
width: 50%;
height: 100px;
margin: 100px auto;
background-color: orange;
overflow: hidden;
}
.tips {
color: #fff;
font-size: 12px;
width: 200px;
margin: auto;
line-height: 20px;
position: absolute;
top: 35px;
left: 50px;
background-color: rgba(24, 22, 22, .8);
display: none;
}
.tips::before {
content: '';
display: inline-block;
position: absolute;
top: -20px;
left: 20px;
border-top: 10px solid transparent;
border-bottom: 10px solid rgba(24, 22, 22, .8);
border-left: 10px solid transparent;
border-right: 10px solid transparent;
}
.relative {
position: relative;
background-color:green;
text-align: center;
width: 100px;
line-height: 25px;
margin: 20px auto 0;
cursor: pointer;
}
.relative:hover .tips {
display: block;
}
.absolute {
position: absolute;
width: inherit;
}
.content {
width: 100%;
height: 20px;
background-color: red;
margin-top: 10px;
}
<div class="container">
<div class="content"></div>
<div class="absolute">
<div class="relative">
鼠标移入
<div class="tips">
我需要超出隐藏1,我需要超出隐藏2,我需要超出隐藏3,我需要超出隐藏4,我需要超出隐藏5,我需要超出隐藏6,我需要超出隐藏7,我需要超出隐藏8,我需要超出隐藏9,我需要超出隐藏10。
</div>
</div>
</div>
</div>
总结
- overflow: hidden有内容溢出来,后面元素紧挨着的属性是absolute
- overflow: hidden没有内容溢出来,在需要使用定位元素前先使用的是relative
第一次记录一下~ ~ ~