垂直对齐两行文字

时间:2015-02-23 15:25:09

标签: html css vertical-alignment

我在div中垂直对齐文本时遇到问题。我已经尝试过我在其他帖子上阅读过的建议。我确定它显而易见我做错了但它不起作用。

http://jsfiddle.net/o6gqvtoo/

<div class="banner">
  <div class="span10"> <!-- bootstrap -->
    <div class="banner-text">
        <div class="pull-left">Here is the first line of text i want to center</div>
        <div class="pull-left">Here is the second line of text i want to center</div>
        <div class="clear"></div>
    </div>
</div>

.banner{
margin-top:-2;
height: 70px;
background-color: #cf0000;
color: white;
height: 70px;
position: relative;
}

.banner-text{
display: block;
vertical-align: middle;
}

.pull-left {
display: block;
}

3 个答案:

答案 0 :(得分:0)

vertical-align有点奇怪。

通常你应该在元素本身而不是它们的容器上使用它,它实际上仅用于内联内联块元素。< / p>

但即便如此,它也许不会像你想要的那样垂直居中(我猜)。所以一个小技巧就是将line-height设置为与height相同并且瞧瞧:

http://jsfiddle.net/06c7eosv/

注意:使用 display:inline-block width:50%,您的元素之间不能有任何空格HTML

好:

<div>...</div><div>...</div>

为:

<div>...</div>
<div>...</div>

答案 1 :(得分:0)

基于提供的图像和可用的有限信息我相信可用的最佳选择是绝对定位横幅文本包装div

&#13;
&#13;
.banner {
  margin-top: -2;
  height: 70px;
  background-color: #cf0000;
  color: white;
  height: 70px;
  position: relative;
}
.banner-text {
  display: block;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.pull-left {
  display: block;
}
&#13;
<div class="banner">
  <div class="span10">
    <!-- bootstrap -->
    <div class="banner-text">
      <div class="pull-left">Here is the first line of text i want to center</div>
      <div class="pull-left">Here is the second line of text i want to center</div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

也就是说,如果两个内部div可以合并,则可以使用其他选项。

答案 2 :(得分:0)

通常,vertical-align设置内联级别元素相对于行框的对齐方式。

但是,在应用于表格单元格时,它具有不同的含义:它设置单元格内容的对齐方式。

因此,您可以使用CSS表格:

.banner {
    display: table;
    width: 100%;
}
.banner > .span10 {
    display: table-row;
}
.banner-text {
    display: table-cell;
    vertical-align: middle;
}

.banner{
  margin-top:-2;
  height: 70px;
  background-color: #cf0000;
  color: white;
  height: 70px;
  position: relative;
  display: table;
  width: 100%;
}
.banner > .span10 {
  display: table-row;
}
.banner-text{
  display: table-cell;
  vertical-align: middle;
}
.pull-left {
  display: block;
  /* float:left; */
}
<div class="banner">
  <div class="span10"> <!-- bootstrap -->
    <div class="banner-text">
      <div class="pull-left">Here is the first line of text i want to center</div>
      <div class="pull-left">Here is the second line of text i want to center</div>
      <div class="clear"></div>
    </div>
  </div>
</div>