我正在尝试垂直对齐青色div中的内容,而不使用以下方法之一:
垂直对齐(因为它需要显示为表格,并且会对父div填充等产生连锁效应)
行高(因为有超过1行,有3个实际跨度)
表格(由于垂直对齐等连锁效应)
绝对定位(因为其他一些青色div将拥有比其他文本更多的文本,这意味着某些文本会比其他文本拥有更多行)
Equal top&底部填充(与abs定位相同的原因)
Flexboxes(我禁止这些因为它们有严重的连锁效应!)
青色div是内联块。实现这一目标的最佳方法是什么?我希望能够在3个跨度中的每一个之间设置填充,以便很好地将它们分开。
注意: 我已经更新了我的答案,包括弹性定位,但在移动视图中,下面的第二个青色div没有集中对齐
.sections {
background: #f2f2f2;
width: 100%;
height: auto;
text-align: center;
padding: 100px 10%;
box-sizing: border-box;
}
h1 {
font-size: 62px;
text-transform: uppercase;
font-weight: 400;
}
p {
font-size: 22px;
font-weight: 300;
padding-top: 10px;
}
.foster-cta {
box-sizing: border-box;
width: 250px;
height: 200px;
background: cyan;
display: inline-block;
border: 1px solid grey;
margin-top: 30px;
/* adding display flex makes the 2nd cyan div below not aligned centrally on mobile view */
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
display: inline-flex;
}
.foster-top {
display: block;
font-size: 30px;
}
.foster-middle {
display: block;
text-transform: uppercase;
font-size: 22px;
}
.foster-bottom {
display: block;
font-weight: 300;
font-size: 16px;
}
<section class="sections">
<h1>header 1 tag</h1>
<p>some random text to go here lorem ipsum sit semei geono wfnwoenfowe fwenfuowe ffe efnpi enfo wfeonwofun weofun weofnwe ofunwe foiej.</p>
<div class="foster-cta">
<span class="foster-top">icon</span>
<span class="foster-middle">some random text here</span>
<span class="foster-bottom">a load more random text goes here that will be more descriptive and longer.</span>
</div><!--
--><div class="foster-cta" style="margin-left:50px;">
<span class="foster-top">icon</span>
<span class="foster-middle">text</span>
<span class="foster-bottom"> a load more random text goes here that will be more descriptive and longer a load more random text goes here that will be more descriptive and longer.</span>
</div>
</section>
答案 0 :(得分:1)
在CSS中进行任何类型的对齐时,Flexbox是您最好的选择。代码也很简单:
.div-parent {
display: flex;
}
.div-child {
align-self: center;
}
这将仅垂直居中对齐