我有一个绝对定位的div,它有两行文本,一个h2和一个p。我试图使文本在绝对定位的div内垂直地居中,对齐,并且在h2和p标记之间有一个行间隔。
绝对定位的div包含在父母中,所以我认为我可以使用flexbox来解决这个问题,但事实证明它比预期的要难。我给出了父显示:flex和对齐项:居中,垂直中心。但是我的h2和p在同一条线上,没有分界线。
因此,我使用了flex方向:列,它创建了一个行符,但是文本不再垂直地居中。如果我使用对齐项:flex端和flex方向:列,文本将对齐,h2和p之间将有一个行间隔,但它们不是垂直中心。
边-右:自动可以对齐项目,但与对齐项目:中心和弯曲方向:列,它不工作。浮子:对也不起作用。
我的标记看起来如下:
<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 -->其中覆盖是绝对定位在覆盖容器内的div。叠加是一个位于图像一部分上的盒子。显示:flex和上面提到的其他属性都在overlay类上。
看来,无论我怎么努力,我只能从这三个条件中得到两个去工作。使用柔性盒并不是一个要求,但我认为它将使它很容易垂直中心的文本。有人能帮忙吗?
发布于 2016-04-23 07:05:14
下面是如何使用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 -->
另一个样本:
https://stackoverflow.com/questions/36807426
复制相似问题