Bootstrap如何使文本在div容器中垂直对齐

23
如何使文本在其列中垂直居中最佳/适当的方法?图像高度在CSS中静态设置。 我尝试将外部div设置为display: table,将内部div设置为display: table-cell,并使用vertical-align: middle,但这也没有起作用。

enter image description here

HTML(超文本标记语言)。
<section id="browse" class="browse">
    <div class="container">
        <div class="row">
            <div class="col-md-5 col-sm-5">
                <h2 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h2>
            </div>
            <div class="col-md-1"></div>
            <div class="col-md-6 col-sm-7 animation_container">
                <img id="animation_img2" class="animation_img animation_img2" src="images/section2img2.png"/>
                <img id="animation_img1" class="animation_img animation_img1" src="images/section2img1.png"/>
            </div>
        </div>
    </div>
</section>

CSS (层叠样式表)
.browse .container, .blind_dating .container { padding-bottom: 0; }
.animation_container { position: relative; }
.browse .animation_container { height: 430px; }
.animation_img { position: absolute; bottom: 0; }
.animation_img1 { right: 25%; }
.animation_img2 { right: 25%; }
3个回答

38

HTML:

首先,我们需要为您的文本容器添加一个类,以便我们可以相应地访问和样式它。

<div class="col-xs-5 textContainer">
     <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>

CSS:

接下来,我们将应用以下样式以垂直对齐它,根据图像 div 旁边的大小。

.textContainer { 
    height: 345px; 
    line-height: 340px;
}

.textContainer h3 {
    vertical-align: middle;
    display: inline-block;
}

完成了!如果您认为它仍然略微不对齐,请在上面的样式中调整行高和高度。

工作示例


@TheNomad - 随时可以!是的,这是一个非常好的技巧,可以记在垂直对齐方面。 - Fizzix

10
h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

解释:

top:50%的样式实际上将标题元素从父元素的顶部向下推出50%。translateY样式也以类似的方式作用,将元素从顶部向下移动50%。

请注意,这对于只有1(也许2)行文本的标题非常有效,因为它仅将标题元素的顶部向下移动50%,然后其余内容填充在其下方,这意味着使用多行文本时,它看起来略微低于垂直对齐。

用于多行的可能修复方法是使用略小于50%的百分比。


0

你不能简单地添加吗:

align-items:center;

将一个新类别添加到您的行(div)中。基本上:
<div class="row align_center">

.align_center { align-items:center; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接