将元素对齐到HTML表格单元格的底部

9

我有一个HTML表格中的单元格里有多个元素。我想让其中一些元素靠单元格底部对齐,另一些元素则靠顶部对齐。但是我在将元素对齐到底部时遇到了问题。我的表格如下:

    <tr>
        <td style="background-color: #007CE2">
            <p id="t1_list">test<br>another<br>testing</p>
            <input type="text" name="t1_input" id="t1_input">
            <button>
                Add
            </button>
        </td>
        <td style="background-color: #E54040">
            <p id="t2_list"></p>
            <div class="value_input2">
                <input type="text" name="t2_input" id="t2_input">
                <button>
                    Add
                </button>
            </div>
        </td>
    </tr>
然而,div内的元素似乎想要保持在单元格中心而不是底部。目前我已经尝试了两种不同的CSS方法:
div.value_input {
    position: absolute;
    bottom: 0;
}

这将把div元素置于页面底部。并且:

div.value_input2 {
    display: table-cell;
    vertical-align: bottom;
}

这没有任何作用。

我在JSFiddle上有代码。

我需要做什么才能使输入框和按钮与单元格底部对齐?

3个回答

9

为了使用绝对定位,您需要将父元素的位置设置为相对位置position:relative。这里是一个可行的代码片段。

table {
      border-collapse: collapse;
  }

  table, th, td {
      border: 2px solid black;
        position:relative;
  }

  div.value_input {
   position: absolute;
      bottom: 0;
  }
    
    div.value_input2 {
      position:absolute;
      bottom:0;
    }
<table>
  <tr>
   <th style="background-color: #007CE2">
    Test
   </th>
   <th style="background-color: #E54040">
    Test
   </th>
  </tr>
  <tr>
   <td style="background-color: #007CE2">
    <p id="t1_list">test<br>another<br>testing</p>
    <input type="text" name="t1_input" id="t1_input">
    <button>
     Add
    </button>
   </td>
   <td style="background-color: #E54040">
    <p id="t2_list"></p>
    <div class="value_input2">
     <input type="text" name="t2_input" id="t2_input">
     <button>
      Add
     </button>
    </div>
   </td>
  </tr>

  <tr>
   <th style="background-color: #8BC34A">
    Test
   </th>
   <th style="background-color: #FF9800">
    Test
   </th>
  </tr>
  <tr>
   <td style="background-color: #8BC34A">
    <p id="t3_list"></p>
    <input type="text" name="t3_input" id="t3_input">
    <button>
     Add
    </button>
   </td>
   <td style="background-color: #FF9800">
    <p id="t4_list"></p>
    <input type="text" name="t4_input" id="t4_input">
    <button>
     Add
    </button>
   </td>
  </tr>
 </table>


3
您需要在此处使用height:somepx才能使垂直对齐生效。

2

将表格单元格的位置设为relative,然后您可以再次尝试在div上使用position: absolute...

table tr td {
  position: relative;
}

div.value_input2 {
  position: absolute;
  bottom: 0;
}

{{链接1:fiddle}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接