有一个父div具有绝对定位,而子级具有绝对定位。 我的问题是使子div相对于整个页面而不是其父页面:
例:
.parent {
position: absolute;
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: blue;
overflow: hidden;
animation: move 2s infinite;
}
.child {
position: fixed;
top: 5px;
left: 5px;
width: 50px;
height: 50px;
background-color: purple;
z-index: 2;
}
@keyframes move {
50% {
transform: translateX(25px);
}
}
<div class="parent">
<div class="child"></div>
</div>
目标是使紫色小div 固定在屏幕左上角,并在蓝色大div 移动到屏幕外时隐藏。我尝试了sticky - fixed
相同的结果。
您可以对子元素使用相反方向的动画,这将使子元素在一个位置看起来像它的静态。
.parent {
position: absolute;
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: blue;
overflow: hidden;
animation: move 2s infinite;
}
.child {
position: absolute;
top: 5px;
left: 5px;
width: 50px;
height: 50px;
background-color: purple;
animation: moveBack 2s infinite;
z-index: 2;
}
@keyframes move {
50% {
transform: translateX(25px);
}
}
@keyframes moveBack {
50% {
transform: translateX(-25px);
}
}
<div class="parent">
<div class="child"></div>
</div>
绝对定位的行为类似于子div 的相对定位。
您必须将子div 移动到父div 之外,以使其相对于页面/正文固定。
否则,child
将始终相对于parent
定位
您可以使用clip-path
动画来考虑一个想法
.parent {
position: absolute;
top: 10px;
left: 10px;
width: 125px;
height: 100px;
background-color: blue;
overflow: hidden;
animation: move 2s infinite;
clip-path:polygon(0 0, calc(100% - 25px) 0,calc(100% - 25px) 100%, 0 100%);
}
.child {
position: absolute;
top: 5px;
left: 5px;
width: 50px;
height: 50px;
background-color: purple;
}
@keyframes move {
50% {
clip-path:polygon(25px 0, 100% 0,100% 100%, 25px 100%);
}
}
<div class="parent">
<div class="child"></div>
</div>
您可以使用此代码
body {
margin: 0;
padding: 0;
}
.parent {
position: absolute;
top: 10px;
left: 10px;
width: 200px;
height: 200px;
background-color: blue;
overflow: hidden;
animation: move 2s infinite;
}
.child {
position: fixed;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
background-color: purple;
z-index: 2;
}
@keyframes move {
50% {
transform: translateX(25px);
}
}
<div class="parent">
<div class="child"></div>
</div>
你的孩子的位置必须是绝对的。绝对定位与页面本身有关。