首页 > 解决方案 > 如何阻止 HTML 表格单元格垂直拉伸?

问题描述

当点击表格中的一个单元格时,会出现一个 X,这是应该的,但我试图阻止表格单元格在发生这种情况时垂直拉伸。单击列中的每个单元格后,单元格将恢复为正常大小,但我需要它,因此单元格永远不会改变大小。

let turn = false;
function play(cell) {
  if (turn == true) {
    cell.innerHTML = 'X';
  } else {
    cell.innerHTML = 'O';
  }

  if (turn == true) {
    turn = false;
  } else {
    turn = true;
  }
}
td {
  background-color: floralwhite;
  text-align: center;
  width: 50px;
  font-size: 100px;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}

table {
  table-layout: fixed;
  border-spacing: 25px;
  width: 750px;
  height: 750px;
  background-color: lightseagreen;
  display: inline-table;
}

#grid {
  float: left;
  margin-top: 50px;
  margin-left: 130px;
}
<div id="grid">
  <table>
    <tbody>
      <tr>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
      </tr>
      <tr>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
      </tr>
      <tr>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
      </tr>
    </tbody>
  </table>
</div>

标签: html

解决方案


默认情况下,HTML 表格应该可以拉伸和缩放以适应里面的内容。这可以通过显式定义高度和宽度来覆盖。所以如果你添加height: 100px;到CSS规则,它会锁定到100pxtd的高度;td

但是等待这仍然不能完全解决它,因为 100 像素字体大小的 X 或 O 的高度使单元格大于 100 像素高。如果您使用浏览器的开发人员工具检查这一点,您会看到一旦在表格单元格中添加了一个字符,单元格高度实际上是 138 像素(至少在 Windows 上的 Chrome 中,这可能在不同的浏览器上略有不同)。为了解决这个问题,您可以将 CSS 中的高度设置为稍高一些,例如 150 像素。另一种选择是使用divs 构建它,而不是在设置显式高度/宽度时不自动扩展。

CSS 如何使 <TD> 固定高度?看起来最一致的解决方法是divs在具有固定高度/宽度的单元格内添加,而不是在td.

let turn = false;

function play(cell) {
  // modified this so you can toggle an empty cell to experiment with heights
  if (cell.innerHTML != '') {
    cell.innerHTML = '';
  } else if (turn) {
    cell.innerHTML = 'X';
  } else {
    cell.innerHTML = 'O';
  }

  turn = !turn;
}
td {
  background-color: floralwhite;
  text-align: center;
  width: 50px;
  font-size: 100px;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
  height: 138px; /* add this */
}

table {
  table-layout: fixed;
  border-spacing: 25px;
  width: 750px;
  height: 750px;
  background-color: lightseagreen;
  display: inline-table;
}

#grid {
  float: left;
  margin-top: 50px;
  margin-left: 130px;
}
<div id="grid">
  <table>
    <tbody>
      <tr>
        <td onclick="play(this)">X</td>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
      </tr>
      <tr>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
      </tr>
      <tr>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
        <td onclick="play(this)"></td>
      </tr>
    </tbody>
  </table>
</div>


推荐阅读