将“按钮高度”设置为父元素的100%,而不设置父高度

问题描述

我有一个div,该div依次包含一个按钮,一个表和另一个按钮,我希望这些按钮位于表的左侧和右侧,并具有与表相同的高度。这些按钮应该是后退按钮,可以更改表中的数据。

我已经接近要在div上使用float: none并在所有项目上使用float: left了,它们可以正确对齐,但是当我在按钮上尝试height: 100%时,它们会在整个窗口,这不是我想要的。

在怪癖模式下,我可以实现类似的功能

div {
    height: 50%;
}
    
button {
    height: 100%;
}
    
table {
    display: inline-block;
}

之所以在意外测试中起作用,是因为我的屏幕尺寸匹配,因此可以按我的意愿显示,但是当我调整窗口大小或添加<!DOCTYPE html>时,情况就改变了。

是否可以使用不使用display: flex方法来完成此任务?

HTML:

<html>
<head>
    <Meta charset="utf-8">
    <title>Under construction</title>
    <link rel="stylesheet" href="../css/stylesheet.css" />
</head>

<body>

<div>
    <button>&larr;</button>

    <table style="border: none">
    <thead><th>a</th><th>b</th><th>c</th></thead>
         <tbody>
             <tr><td>A</td><td>B</td><td>C</td></tr>
             <tr><td>D</td><td>E</td><td>F</td></tr>
             <tr><td>G</td><td>H</td><td>I</td></tr>
         </tbody>
    </table>

    <button>&rarr;</button>
</div>

</body>

</html>

CSS:

td {
    background: green;
    border-radius: 7px;
}

解决方法

position:absolute似乎是这里的 only 解决方案:

td {
  background: green;
  border-radius: 7px;
}
.box  {
  border:1px solid red;
  position:relative;
  display:inline-block;
  padding:0 50px; /* 50px is considered to be the width of button so adjust it based on your case*/ 
}
.box button {
  position:absolute;
  top:0;
  height:100%;
  left:0;
}
.box button:last-of-type {
  left:auto;
  right:0;
}
<div class="box">
  <button>&larr;</button>

  <table style="border: none">
    <thead>
      <th>a</th>
      <th>b</th>
      <th>c</th>
    </thead>
    <tbody>
      <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
      </tr>
      <tr>
        <td>D</td>
        <td>E</td>
        <td>F</td>
      </tr>
      <tr>
        <td>G</td>
        <td>H</td>
        <td>I</td>
      </tr>
    </tbody>
  </table>

  <button>&rarr;</button>
</div>

或者您可以考虑其他表结构,但是您需要调整HTML代码:

.box table td {
  background: green;
  border-radius: 7px;
}

.box {
  border: 1px solid red;
  border-spacing: 0;
}
.box,.box > tbody,.box > tbody > tr > td{
  height:100%;
}

.box button {
  height: 100%;
}
<table class="box">
  <tr>
    <td><button>&larr;</button></td>

    <td>
      <table style="border: none">
        <thead>
          <th>a</th>
          <th>b</th>
          <th>c</th>
        </thead>
        <tbody>
          <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
          </tr>
          <tr>
            <td>D</td>
            <td>E</td>
            <td>F</td>
          </tr>
          <tr>
            <td>G</td>
            <td>H</td>
            <td>I</td>
          </tr>
        </tbody>
      </table>
    </td>
    <td><button>&rarr;</button></td>
  </tr>
</table>