使用 top: 50%; 实现垂直居中的绝对定位,需要再加上 transform: translateY(-50%);。代码如下:

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

其中,parent 是父元素,child 是要垂直居中的子元素。注意,父元素必须是相对定位,否则子元素的 top: 50%; 将会相对于页面顶部而不是父元素顶部。

使用 transform: translateY(-50%); 是因为 top: 50%; 让子元素的顶部与父元素的中心对齐,而 translateY(-50%); 将子元素的中心向上移动了自身高度的一半,从而实现了垂直居中。

css绝对定位垂直居中 top 50;

原文地址: https://www.cveoy.top/t/topic/bsTx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录