【问题标题】:How to vertical align middle two elements in same table cell如何垂直对齐同一表格单元格中的中间两个元素
【发布时间】:2017-12-31 11:01:27
【问题描述】:

我有一个有 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 是文本的高度,因此垂直对齐文本不会移动它。有没有其他方法可以实现这一目标?感谢您提供的任何帮助!

【问题讨论】:

标签: html css


【解决方案1】:

是的,你可以使用 :before,但你必须为你的 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>

【讨论】:

    【解决方案2】:

    您可以使用弹性框。

    .container {
      display: flex;
      align-items: center;
    }
    
    .container button {
      margin-left: .5em;
    }
    <td>
      <div class="container">
        <div>
          Text Not In Middle Of Cell
        </div>
        <div>
          <button type="button">Button Text</button>
        </div>
      </div>
    </td>

    【讨论】:

    • 请注意,在 IE 11 中并不完全支持 display: flex。对于需要仔细检查跨浏览器支持的任何人,请参阅 caniuse.com。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2016-09-19
    • 2016-05-15
    • 2013-06-12
    相关资源
    最近更新 更多