如何在表内输入时将标签垂直居中

  • 本文关键字:标签 垂直居中 css
  • 更新时间 :
  • 英文 :


有没有办法在输入中垂直居中这个标签?我确实尝试过表格/表格单元格的方法,但在这里不起作用。

html:

<table class="header-table">
  <tbody>
    <tr>
      <td class="column-2">
        <label>asdf</label>
        <input>
      </td>
    </tr>
  </tbody>
</table>

css:

.header-table .column-2 label {
  position: absolute;
}
.header-table .column-2 input {
  height: 32px;
}

https://jsfiddle.net/tombrito/aj6eb2v6/6/

你可以试试这个:

.header-table .column-2 {
    position: relative;
}
.header-table .column-2 label {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.header-table .column-2 input {
  height: 32px;
}
<!-- placeholder vertical centered -->
<table class="header-table">
  <tbody>
    <tr>
      <td class="column-2">
        <label>asdf</label>
        <input>
      </td>
    </tr>
  </tbody>
</table>

使用transformtop垂直偏移标签。这样做将根据元素的大小自动缩放。无需猜测偏移量等:)

在浏览器中也得到了很好的支持-http://caniuse.com/#search=transform

您的绝对位置当前不是相对于它所在的单元格。

.header-table .column-2{
  position:relative;
}
.header-table .column-2 label {
  position: absolute;
  top:50%;
  margin-top:-11px;
  height:100%;
}
.header-table .column-2 input {
  height: 32px;
  line-height:32px;
}
<!-- placeholder vertical centered -->
<table class="header-table">
  <tbody>
    <tr>
      <td class="column-2">
        <label>asdf</label>
        <input>
      </td>
    </tr>
  </tbody>
</table>

由于容器的高度为32px,因此可以为标签指定32px行高度。这可能是一个简单的技巧,因为你不必担心浏览器支持。

参见

.header-table .column-2 label {
  position: absolute;
  line-height: 32px;
}
.header-table .column-2 input {
  height: 32px;
}
td.column-2 {
  position: relative;
}
<!-- placeholder vertical centered -->
<table class="header-table">
  <tbody>
    <tr>
      <td class="column-2">
        <label>asdf</label>
        <input>
      </td>
    </tr>
  </tbody>
</table>

最新更新