我有一个高度可变的容器,并希望在其中间放置一个元素。因此,我设置了以下样式:
#parent {
position: relative;
}
#child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
这个方法在大多数情况下可行。然而,容器的高度不仅是可变的,而且还会不断变化。
因此,那段代码不起作用。以下是一个示例:
@keyframes changeSize {
0% {
height: 100px;
}
50% {
height: 150px;
}
100% {
height: 100px;
}
}
#parent {
position: relative;
width: 400px;
height: 300px;
background: red;
animation-name: changeSize;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
#child {
position: absolute;
margin-block-start: 0;
margin-block-end: 0;
right: 0;
top: 50%;
transform: translateY(-50%);
}
<div id="parent">
<p id="child">I should not be moving...</p>
</div>
正如您所看到的,它正在移动。那么,我的问题是,有没有一种方法可以将其垂直放置在元素的中间,但不会因容器大小改变而移动 - 只需使用CSS?