19

什么是垂直对齐列中间文本的最佳方式?图像高度在CSS中静态设置。Bootstrap如何让文本垂直对齐在div容器中

我已经尝试设置一个外部div到display: table和一个内部div到display: table-cellvertical-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%; } 

回答

32

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:

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

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

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

全部完成!如果您认为它仍然略微偏离对齐,请调整上述样式的线条高度和高度。

WORKING EXAMPLE

+1

非常感谢!很高兴知道'line-height'技巧! – 2014-08-28 00:28:29

+0

@TheNomad - 任何时候!是的,记住垂直对齐是一个很好的技巧。 – Fizzix 2014-08-28 00:29:32

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

说明:

顶部:50%风格基本上推动头部元素下降50%从父元素的顶部。 translateY样式也以类似的方式将元素从顶部向下移动50%。

请注意,这可以很好地用于标头1(也许2)行文字,因为这只是使得接头元件降50%的顶部,然后在下面所述内容的其余部分填充,这意味着多行文字看起来会略低于垂直对齐。

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

+1

请尝试解释更多关于这是如何工作的 – Markasoftware 2014-08-28 01:10:35

+1

@Markasoftware添加了一些编辑和一些解释 – Brian 2014-08-28 17:37:24

-1

你能不能简单地说:

align-items:center; 

到一个新的类在你行格。基本上:

<div class="row align_center"> 

.align_center { align-items:center; }