【问题标题】:Positioning a div relative to its vertical centre [duplicate]相对于其垂直中心定位 div [重复]
【发布时间】:2018-01-15 20:24:42
【问题描述】:

我有一条欢迎消息,需要将其中心定位在距窗口顶部 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 相对于其垂直中心定位。任何帮助将不胜感激!

想要的定位: 当前定位:

【问题讨论】:

  • 我已经编辑了我的两个定位的答案(您当前拥有的一个和更正的一个)

标签: html css vertical-alignment positioning


【解决方案1】:

使用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>

【讨论】:

  • 为什么是 -75% 而不是 -50%?
  • @ManuelOtto 已更正
【解决方案2】:

这应该可行。我将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>

【讨论】:

    【解决方案3】:

    在下面的 sn-p 中,我有两个元素,都设置为 position:absolutetop: 25%left: 50%

    • .elementtransform: translate(-50%, -50%); 一样,允许他在页面尺寸(高度、宽度)的 25% 处“完全”垂直和水平居中。因为与topleft 不同,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>

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 2014-01-29
      • 2018-10-24
      • 1970-01-01
      相关资源
      最近更新 更多