相对于其垂直中心定位 div

Positioning a div relative to its vertical centre

我有一条欢迎消息,需要将其中心定位在距离 window 顶部 25% 的位置。因为它可以是任意数量的线,所以需要使用它的垂直中心来定位它。这是我目前拥有的。

.welcomeMessage {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  margin: auto;
  width: 60%;
  top: 25%;
}

我尝试过使用 display: inline-block 和 display: flex with vertical-align: middle 但都没有将 div 定位到其垂直中心。任何帮助将不胜感激!

所需定位: 目前定位:

使用transform:translate(-50%);

margin: auto; 不适用于 inline-block 元素,因此您需要添加 left:50% 使其水平居中。

html,body{
  height:100%;
  margin:0;
  padding:0;
}

.welcomeMessage {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  left:50%;
  width: 60%;
  top: 25%;
  transform:translate(-50%);
}
<div class="welcomeMessage">Welcome Message</div>

这应该可行。我将 h1 的大小定义为 2em 并计算顶部位置,字体大小减半后减少 25%。

.container {
  width: 100vw;
  height: 100vh;
  background: lightgray;
}

.h1 {
  font-size: 2em;
}

.welcomeMessage {
  position: absolute;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  margin: auto;
  width: 60%;
  top: calc(25% - 1em)
}
<div class="container"></div>
<h1 class="welcomeMessage">Welcome</h1>

在下面的代码片段中,我有两个元素,都设置为 position:absolutetop: 25%left: 50%

  • .element as transform: translate(-50%, -50%); that allows him to center vertically and horizontally "exactly" at 25% of the page dimensions (height, width). Because unlike top and left, the transform 属性 是基于目标元素的大小。所以你设置的百分比是指目标边界框的大小。
  • 另一方面,
  • .other 没有 transform 规则,因此它的位置不像您想要的那样,它的上边框位于 25%

.element,
.other {
  position: absolute;
  text-align: center;
  top: 25%;
  left: 50%;
}

.element {
  transform: translate(-50%, -50%);
  color: green;
}

.other {
  color: red;
}
html,body{
  height:100%;
  margin:0;
  padding:0;
}
<div class="element">I'm at 25% middle</div>
<div class="other">I'm not at 25% middle</div>