【问题标题】:Postion a child element absolute to the page, even when the absolute positioned parent is moved将子元素定位到页面的绝对位置,即使移动了绝对定位的父元素
【发布时间】:2020-05-10 19:23:59
【问题描述】:
我将容器定位到页面的绝对位置。在这个容器中,我还需要将一个 span 定位到页面的绝对位置,因为如果它在移动后溢出父容器,我想隐藏它。
它应该看起来像this。
我只能隐藏跨度,如果它是一个孩子并且父母隐藏了它的溢出。但是我不能将两者都定位为绝对值。
我当前的代码如下所示:
.container {
overflow: hidden;
position: absolute;
width: 150px;
height: 50px;
background-color: black;
animation: move 2s ease-in-out alternate infinite;
}
.container span {
position: absolute;
left: 20px;
top: 20px;
color: white;
font-size: 16px;
}
@keyframes move {
0% {
top: 0;
}
100% {
top: 200px;
}
}
<div class="container">
<span>Text</span>
</div>
【问题讨论】:
标签:
javascript
html
css
css-animations
【解决方案1】:
.container {
overflow: hidden;
position: absolute;
width: 150px;
height: 50px;
background-color: black;
animation: move 2s ease-in-out alternate infinite;
}
.container span {
position: absolute;
left: 20px;
top: 20px;
color: white;
font-size: 16px;
animation: move2 2s ease-in-out alternate infinite;
}
@keyframes move {
0% {
top: 0;
}
100% {
top: 200px;
}
}
@keyframes move2 {
0% {
top: 0;
}
100% {
top: -200px;
}
}
<div class="container">
<span>Text</span>
</div>
【解决方案2】:
对孩子使用position:fixed 并考虑clip-path 而不是溢出来隐藏溢出:
.container {
clip-path:polygon(0 0,100% 0,100% 100%,0 100%);
position: absolute;
width: 150px;
height: 50px;
background-color: black;
animation: move 2s ease-in-out alternate infinite;
}
.container span {
position: fixed;
left: 20px;
top: 20px;
color: white;
font-size: 16px;
}
@keyframes move {
0% {
top: 0;
}
100% {
top: 200px;
}
}
body {
background:blue;
}
<div class="container">
<span>Text</span>
</div>