如何在同一个表格单元格中垂直对齐中间两个元素

时间:2017-07-25 13:21:34

标签: html css

我有一个包含5列的表,所有列都是垂直对齐的:中间。前4列仅包含在单元格中间垂直对齐的文本。前四列格式很好;但是,最后一个单元格由两个div组成。第一个是向左浮动的文本,第二个是向右浮动的按钮。这是最后一个单元格的html:

 <td>
        <div style="float:left; width:50%">
              Text Not In Middle Of Cell
        </div>
        <div style="float:right; width:50%">
               <button type="button">Button Text</button>
        </div>
    </td>

查看下面的图片,您可以看到文本未在单元格的中间垂直对齐。有没有办法将文本集中在它所居住的单元格的中心?我试过在div中添加vertical-align:middle但是没有用。这是有道理的,因为div是文本的高度,所以垂直对齐文本不会移动它。有没有其他方法来实现这一目标?感谢您提供的任何帮助!

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用弹性箱。

&#13;
&#13;
.container {
  display: flex;
  align-items: center;
}

.container button {
  margin-left: .5em;
}
&#13;
<td>
  <div class="container">
    <div>
      Text Not In Middle Of Cell
    </div>
    <div>
      <button type="button">Button Text</button>
    </div>
  </div>
</td>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

是的,您可以使用:之前,但您必须为div设置高度

这是一个示例代码

     .text_div{
       float:left;
       width:50%;
       height: 100px;
       background-color:#f00;
	}
	.text_div:before {
		content: ' ';
		display: inline-block;
		vertical-align: middle;
		height: 100%;
	}
	.text_div{
		vertical-align: middle;
		display: inline-block;
	}
<td>
    <div class="text_div">
        <a>Text Not In Middle Of Cell</a>
    </div>
    <div style="float:right; width:50%">
           <button type="button">Button Text</button>
    </div>
</td>