Joh*_*ohn 2 css vertical-alignment right-align flexbox
我有一些绝对定位的div有两行文字,一个h2和一个p.我试图让文本成为:在绝对定位的div中垂直居中,右对齐,并且在h2和p标签之间存在换行符.
绝对定位的div包含在母公司内,所以我想我可以用Flexbox,就解决了这个问题,但原来它更难于预期.我已经给出了父显示:flex和align-items:center,它们垂直居中.但是后来我的h2和p在同一条线上,没有换行符.
那么我使用了flex-direction:column创建了一个换行符,但是文本不再是垂直居中的.如果我使用align-items:flex-end和flex-direction:列,文本将右对齐,并且在h2和p之间会有换行符,但是它们不会垂直居中.
margin-right:auto可以正确对齐项目,但结合align-items:center和flex-direction:列,它不起作用.float:右边也行不通.
我的标记看起来像这样:
<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 -->
Run Code Online (Sandbox Code Playgroud)
overlay是overlay-container中绝对定位的div.覆盖图是位于图像的一部分上方的框.显示:上面提到的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;
}Run Code Online (Sandbox Code Playgroud)
<div class = "overlay overlay-2">
<h2>Recent Work</h2>
<p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->Run Code Online (Sandbox Code Playgroud)
更新
在某些情况下,可能需要使用自动边距,因为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 */
}Run Code Online (Sandbox Code Playgroud)
<div class = "overlay overlay-2">
<h2>Recent Work</h2>
<p>Lorem ipsum dolor</p>
</div> <!-- /overlay -->Run Code Online (Sandbox Code Playgroud)
更新2
这里有一个中间的第3项,当不合适时会滚动什么.
堆栈代码段
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 */
}Run Code Online (Sandbox Code Playgroud)
<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 -->Run Code Online (Sandbox Code Playgroud)
另一个样本: