保持百分比元素的位置固定为fixed

3

我有一个高度可变的容器,并希望在其中间放置一个元素。因此,我设置了以下样式:

#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?


我认为解决这个问题的唯一途径是使用JavaScript。#child上的百分比单位是相对于包含元素的。由于包含元素的高度在改变,因此您会注意到单位的变化。 您需要使用固定单位(如像素)。获取像素初始50%读数的唯一方法是使用JavaScript。正在编写答案... - www139
如果高度最初是固定的,为什么不直接使用它来定义顶部值呢? - Temani Afif
1个回答

2
问题在于百分比的度量单位是相对于包含元素而言的。由于#parent通过动画改变高度,因此百分比单位的值也会发生变化。这种单位变化会影响应用于#child的百分比高度属性。解决方法可能是一些非常复杂的CSS(可能不适用于每种情况),因此最好的解决方案是使用JavaScript来捕获初始50%高度的像素值,以便单位不再发生变化。同样重要的是,使用一个resize事件监听器,如果浏览器窗口大小被调整,则应用一个新的50%高度。

window.addEventListener('load',resizeDiv());
window.addEventListener('resize',resizeDiv());

function resizeDiv(){
  var initialHeight = document.getElementById('parent').offsetHeight/2;
  document.getElementById('child').style.top = initialHeight+'px';
}
@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;
}
<div id="parent">
  <p id="child">Hey!! I'm not moving anymore!</p>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接