为什么需要translateY(-50%)来将顶部的元素居中:50%?

2024-04-05

我可以看到这段代码可以在其父元素内垂直对齐 div:

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

问题是为什么?我的第一个想法是父元素包含的不仅仅是视口。我让我的父视口高度相等100vh和宽度100%。那没有用。我仍然需要翻译或负边距偏移。为什么当父元素设置为时需要负偏移margin: 0;?是因为我没有考虑计算出的边际吗?


top:0 (默认)

默认情况下,你的元素位于页面顶部,并且元素的顶部位于 0 处:

--------Top of Page--------
{element}


------Middle of  Page------



------Bottom of  Page------

top:50%

当您将其向下移动 50% 高度(整个页面的 50%)时,元素的顶部位于 50% 标记处,这意味着元素从 50% 开始并且不居中。

--------Top of Page--------



------Middle of  Page------
{element}


------Bottom of  Page------

顶部:50%;变换:平移Y(-50%);

当元素的顶部位于中间标记时,我们可以将元素向后移动其自身高度的一半,以使其与整个页面居中。正是如此transform:translateY(-50%); does:

--------Top of Page--------



{element}-Middle of Page---



------Bottom of  Page------

但为什么我们不能直接说top: 25%或类似的东西?我制作了一个快速片段来向您展示该实现的差异:

body {
  margin: 0;
}
.row {
  display: flex;
  justify-content: space-between;
}
.container {
  display: inline-block;
  margin: 5px;
  width: 200px;
  height: 200px;
  background: tomato;
}
.inner {
  position: relative;
  margin: 0 auto;
  height: 50%;
  width: 50%;
  background: #FFC4BA;
}
.inner.small {
  width: 25%;
  height: 25%;
}
.inner.big {
  width: 75%;
  height: 75%;
}
.percent {
  top: 25%
}
.transform {
  top: 50%;
  transform: translateY(-50%);
}
<b>First row </b>looks alright, but that's because the gap works well with the 25%
<div class="row">
  <div class="container">
    <div class="inner percent"></div>
  </div>
  <div class="container">
    <div class="inner transform"></div>
  </div>
</div>
<b>Second row </b>made the center square a bit smaller, and the 25% now is too high as we'd expect the bottom of the element to reach 75%
<div class="row">
  <div class="container">
    <div class="small inner percent"></div>
  </div>
  <div class="container">
    <div class="small inner transform"></div>
  </div>
</div>
<b>Third row </b>now I've made the center box big and it ends lower than 75% making 25% start too late
<div class="row">
  <div class="container">
    <div class="big inner percent"></div>
  </div>
  <div class="container">
    <div class="big inner transform"></div>
  </div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么需要translateY(-50%)来将顶部的元素居中:50%? 的相关文章