【问题标题】:how to vertical align middle to multiple position absolute child div如何将中间垂直对齐到多个位置绝对子div
【发布时间】:2018-04-25 16:32:45
【问题描述】:

我目前面临将多个位置垂直对齐的问题:绝对 div 到中间。虽然我应用了宽度:100% 和高度:100%,但元素似乎也溢出了。请帮我解决这个问题。谢谢。

<div class="wrapper">
  <div class="wrapper-inner">
    <div class="section-1">
      <h2>Heading Here</h2>
      <p>Some text here</p>
    </div>
    <div class="section-2">
      <p>Another text here.</p>
      <p>One more time.</p>
    </div>
  </div>
</div>

html,
body {
  width: 100%;
  height: 100%;
}
.wrapper {
  width: 100%;
  height: 100%;
}
.wrapper-inner {
  width: 100%;
  height: 100%;
  position: relative;
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}

演示:https://codepen.io/rae0724/pen/jamzbX

除了 top:50% 和减去它的高度外,我找不到在当前位置和中间位置制作这些内容的方法,但不利于响应。

【问题讨论】:

  • 你所需要的只是节类相对于屏幕高度垂直对齐到中间,对吗?

标签: jquery html css center


【解决方案1】:

尝试使用 CSS 定位。喜欢:

.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.wrapper-inner {
  position: absolute;
  top: 50%;
  transform: translateY(-41px);
}

看看下面的sn-p:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.wrapper-inner {
  position: absolute;
  top: 50%;
  transform: translateY(-41px);
}
.section-1 {
  position: absolute;
  left: 20vw;
  width: 40vw;
  background: #ccc;
}
.section-2 {
  position: absolute;
  left: 60vw;
  background: #375642;
  width: 40vw;
}
<div class="wrapper">
  <div class="wrapper-inner">
    <div class="section-1">
      <h2>Heading Here</h2>
      <p>Some text here</p>
    </div>
    <div class="section-2">
      <p>Another text here.</p>
      <p>One more time.</p>
    </div>
  </div>
</div>

希望这会有所帮助!

【讨论】:

  • 嗨,如果我想让内容居中,它可以工作,但实际上我想成为那个特定的位置。
  • .section-1 在左边:20vw 而.section-2 在左边:60vw
  • 哦,这就是我知道的方式。它对于响应式内容不够灵活。我正在寻找一种有效的方法
  • 我的意思是,如果我的内容高度是 200 像素(如果调整为移动尺寸),但 translateY 不是流畅的,而只是自适应
【解决方案2】:

如果您需要以 section 开头的所有类垂直居中,则:

CSS:

div[class^='section-'], div[class*='section-']{
    position: absolute;
    left: 20vw;
    width: 40vw;
    background: #ccc;
    top: 50%;
    transform: translateY(-50%);
}

% 中添加顶部和变换值应该可以解决问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2010-12-12
    相关资源
    最近更新 更多