【问题标题】:How to vertically align text in the middle of two divs如何垂直对齐两个div中间的文本
【发布时间】:2014-09-05 21:54:07
【问题描述】:

我正在尝试在 boxes div 的中间垂直对齐 + 符号,但是我无法让它工作。我究竟做错了什么?我也想避免使用表格。谢谢(我还附上了codepen链接)

<div class="boxes">
   <div class="boxes_box">
   </div>
   <div class="boxes_plus">+</div>
   <div class="boxes_box">
   </div>
</div>

CSS

.boxes {
  height: 250px;
}
.boxes_box {
  width: 250px;
  height: 250px;
  display:inline-block;
  background:#000;
}
.boxes_plus {
  display:inline-block;
  height:250px;
  line-height:250px;
  vertical-align:middle;
}

http://codepen.io/anon/pen/aoiGm

【问题讨论】:

  • 对不起,我忘了说我想先避开桌子

标签: css


【解决方案1】:

使用这个:

.boxes {
  height: 250px;
  display:table;/*Add display table*/
}
.boxes_box {
  width: 250px;
  height: 250px;
  display:inline-block;
  background:#000;
  display:table-cell;/*display table cell here is not necessary*/
}
.boxes_plus {
  display:inline-block;
  height:250px;
  line-height:250px;
  vertical-align:middle;
  display:table-cell;/*Add display table cell*/
}

fiddle

您可以简单地删除line-height

.boxes_plus {
  display:inline-block;
  height:250px;
  /*line-height:250px;*/
  vertical-align:middle;
}

fiddle

【讨论】:

  • 不管怎样不用桌子? (忘了说,抱歉)
【解决方案2】:
<style>
.boxes {
  height: 250px;
  display:table;
}
.boxes_box {
  width: 250px;
  height: 250px;
  display:table-cell;
  background:#000;
}
.boxes_plus {
  display:table-cell;
  height:250px;
  line-height:250px;
  vertical-align:middle;
}
</style>

【讨论】:

  • 我正要向朋友提出完全相同的建议! >:3
【解决方案3】:

对于现有的最小更改,请将.box_plusvertical-align 更改为top

http://codepen.io/jwhitfieldseed/pen/FeJco

解释:line-height 将“+”文本放在.boxes_plus 的垂直中心。

文本已经在其容器中垂直居中,因此您现在需要使.boxes_plus 的顶部与.boxes_box 的顶部对齐。

【讨论】:

  • 谢谢,它帮助我理解了它到底是做什么的
【解决方案4】:

请按照以下方式更新您的 css

.boxes {
  height: 250px;
  display: table
}
.boxes_box {
  width: 250px;
  height: 250px;
  display:table-cell;
  background:#000;
}
.boxes_plus {
  display:table-cell;
  height:250px;
  line-height:250px;
  vertical-align:middle;
}

http://codepen.io/anon/pen/crBea

【讨论】:

    【解决方案5】:

    试试这个:

    DEMO

    .boxes {
      height: 250px;
      display:table;
    }
    .boxes_box {
      width: 250px;
      height: 250px;
      display:inline-block;
      background:#000;
    }
    .boxes_plus {
      display:table-cell;
      height:250px;
      line-height:250px;
      vertical-align:middle;
    }
    

    【讨论】: