我有一些绝对定位的 div,有两行文本,一个 h2 和一个 p。我试图让文本:在绝对定位的 div 内垂直居中,右对齐,并且 h2 和 p 标签之间有一个换行符。
绝对定位的 div 包含在父级中,所以我想我可以使用 flexbox 来解决这个问题,但事实证明它比预期的更难。我已经给了父显示器: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/[email protected] /cdn-cgi/l/email-protection" 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和其他属性都在overlay类上。
看来无论我怎么尝试,我只能让这三个条件中的两个起作用。使用 Flexbox 不是必需的,但我认为它可以轻松地将文本垂直居中。有人可以帮忙吗?
这是如何使用居中的示例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 -->
Updated
在某些情况下,可能需要使用自动边距,作为居中时的默认行为justify-content
(当使用flex-direction: column
)是,当内容放不下时,它会在顶部和底部溢出。
- https://www.w3.org/TR/css-flexbox-1/#valdef-justify-content-center https://www.w3.org/TR/css-flexbox-1/#valdef-justify-content-center
堆栈片段
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 -->
另一个样本:
- 如何使用flex css固定div内内容的高度 https://stackoverflow.com/questions/48462423/how-to-fix-height-the-content-inside-a-div-with-flex-css/48462612#48462612
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)