3

我有一些绝对定位的 div,其中包含两行文本,一个 h2 和一个 p。我试图让文本:在绝对定位的 div 中垂直居中,右对齐,并且在 h2 和 p 标签之间有一个换行符。

绝对定位的 div 包含在父级中,所以我想我可以使用 flexbox 来解决这个问题,但结果比预期的要难。我给了父 display:flex 和 align-items:center ,它们垂直居中。但是我的 h2 和 p 在同一行,没有换行符。

所以然后我使用了 flex-direction: column 创建了一个换行符,但是文本不再垂直居中。如果我使用 align-items:flex-end 和 flex-direction:column 文本将右对齐,并且在 h2 和 p 之间会有换行符,但它们不会垂直居中。

margin-right:auto 据说可以右对齐项目,但与 align-items:center 和 flex-direction:column 结合使用,它不起作用。float:right 也不起作用。

我的标记如下所示:

    <div class = "col-sm-12">
      <div class = "row overlay-container">
        <img src = "_img/top-right@4x.png" class = "img-responsive grid-image" alt = "top-right@4x image" />
          <div class = "overlay overlay-2">
           <h2>Recent Work</h2>
           <p>Lorem ipsum dolor</p>
         </div> <!-- /overlay -->
      </div> <!-- /row -->
    </div> <!-- /top right -->

其中overlay是overlay-container内绝对定位的div。叠加层是位于图像一部分上的框。上面提到的 display:flex 和其他属性都在覆盖类上。

看来无论我怎么尝试,都只能得到三个条件中的两个来工作。使用 flexbox 不是必需的,但我认为它可以很容易地将文本垂直居中。任何人都可以帮忙吗?

4

1 回答 1

5

这是一个如何使用居中的示例display: flex

堆栈片段

body {
  margin: 0;
}
.overlay {
  width: 300px;
  margin-top: 5vh;
  height: 90vh;
  border: 1px solid;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;  
}
<div class = "overlay overlay-2">
  <h2>Recent Work</h2>
  <p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->


更新

在某些情况下,可能需要使用自动边距,因为使用justify-content(使用时flex-direction: column)居中时的默认行为是,当内容不适合时,它会在顶部和底部溢出。

堆栈片段

body {
  margin: 0;
}
.overlay {
  width: 300px;
  margin-top: 5vh;
  height: 90vh;
  border: 1px solid;
  
  display: flex;
  flex-direction: column;
  /*justify-content: center;        removed  */
  align-items: center;  
  overflow: auto;               /*  scroll when overflowed  */
}

.overlay h2 {
  margin-top: auto;             /*  push to the bottom  */
}
.overlay p {
  margin-bottom: auto;          /*  push to the top  */
}
<div class = "overlay overlay-2">
  <h2>Recent Work</h2>
  <p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->


更新 2

这里中间有第三个项目,不适合时会滚动。

堆栈片段

body {
  margin: 0;
}
.overlay {
  width: 300px;
  margin-top: 5vh;
  height: 90vh;
  border: 1px solid;
  
  display: flex;
  flex-direction: column;
  align-items: center;  
}

.overlay p:first-of-type {
  overflow: auto;               /*  scroll when overflowed  */
}

.overlay h2 {
  margin-top: auto;             /*  push to the bottom  */
}
.overlay p:last-of-type {
  margin-bottom: auto;          /*  push to the top  */
}
<div class = "overlay overlay-2">
  <h2>Recent Work</h2>
  <p>
    Lorem ipsum dolor<br>
    Lorem ipsum dolor<br>
    Lorem ipsum dolor<br>
    Lorem ipsum dolor<br>
    Lorem ipsum dolor<br>
    Lorem ipsum dolor<br>
    Lorem ipsum dolor<br>
  </p>
  <p>Maybe a link for more</p>
</div> <!-- /overlay -->


另一个样本:

于 2016-04-23T07:05:14.113 回答