html - 如何阻止 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 表格应该可以拉伸和缩放以适应里面的内容。这可以通过显式定义高度和宽度来覆盖。所以如果你添加height: 100px;
到CSS规则,它会锁定到100pxtd
的高度;td
但是等待这仍然不能完全解决它,因为 100 像素字体大小的 X 或 O 的高度使单元格大于 100 像素高。如果您使用浏览器的开发人员工具检查这一点,您会看到一旦在表格单元格中添加了一个字符,单元格高度实际上是 138 像素(至少在 Windows 上的 Chrome 中,这可能在不同的浏览器上略有不同)。为了解决这个问题,您可以将 CSS 中的高度设置为稍高一些,例如 150 像素。另一种选择是使用div
s 构建它,而不是在设置显式高度/宽度时不自动扩展。
每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>
推荐阅读
- amazon-web-services - 尽管端口已打开,但无法通过浏览器访问 Prometheus
- datatables - 如何使第二个标题行可见为 Datatable 中的第一个标题行?
- angular - 错误:找不到模块:错误:无法解析“项目路径”中的“ngx-bootstrap/component-loader/component-loader.factory”
- python - 在 for 循环中更改字符串列表
- typescript - Jest 测试套件失败并显示消息“未定义自我”
- android - 我无法使用后退按钮关闭我的应用程序,因为 onKeyDown() 方法
- sql - 在 oracle 中优化 Group BY
- android - 错误:Kotlin 中基因类型的 [Dagger/DuplicateBindings]
- python - 在多个 excel 行中查找单词时的获取和错误
- python - For循环没有正确写入列表?