You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使表格输入表单中的删除按钮与其他控件尺寸一致?

解决表格内删除按钮与其他控件尺寸匹配及对齐问题

核心修改点

  • 给表格单元格(td)设置垂直居中对齐,统一内部控件的排布基准
  • 调整删除按钮的内边距,使其高度与输入框、复选框匹配
  • 统一控件的盒模型与间距,避免布局偏移

修改后的完整代码

HTML 部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <form method="get" id="form">
    <table id="records">
      <thead>
        <tr>
          <th>Name</th>
          <th>Show</th>
          <th>
            <button type="button" onclick="addRecord()">+</button>
          </th>
        </tr>
      </thead>
      <tbody> </tbody>
    </table>
  </form>
</body>
</html>

CSS 部分

th {
  font-size: 1.1em;
  padding: 0 5px;
}

/* 给表格单元格设置垂直居中,统一内边距 */
td {
  vertical-align: middle;
  padding: 4px;
}

button,
input {
  font-family: inherit;
  font-size: 100%;
  box-sizing: border-box;
  appearance: none;
}

input {
  padding: 5px;
  border: 2px solid lightblue;
  border-radius: 5px;
}

button {
  border: none;
  background-color: lightblue;
  color: white;
  border-radius: 4px;
  font-size: 1.3em;
  /* 设置与输入框匹配的内边距,替代height:100% */
  padding: 3px 8px;
  /* 确保按钮在单元格内垂直居中 */
  vertical-align: middle;
}

input[type="checkbox"] {
  position: relative;
  width: 2em;
  height: 2em;
  background-color: lightblue;
  vertical-align: middle;
  color: white;
}

input[type="checkbox"]::before {
  content: "✔";
  position: absolute;
  font-size: 2em;
  right: 0px;
  top: -0.3em;
  visibility: hidden;
}

input[type="checkbox"]:checked::before {
  visibility: visible;
}

JavaScript 部分

'use strict';

function addRecord() {
  const table = document.getElementById('records').tBodies[0];
  const tr = table.insertRow();
  let td = tr.insertCell();
  td.innerHTML = '<input type="text" name="name" placeholder="Name">';
  td = tr.insertCell();
  td.innerHTML = '<input type="checkbox" name="show" checked>';
  td = tr.insertCell();
  td.innerHTML = '<button type="button" onclick="removeRow(this)">🗙</button>';
}

function removeRow(btn) {
  btn.closest("table").deleteRow(btn.closest("tr").rowIndex);
}

window.onload = (event) => {
  addRecord();
};

关键调整说明

  1. 单元格垂直对齐:给td添加vertical-align: middle,让所有控件在单元格内垂直居中,解决按钮和复选框上下偏移的问题。
  2. 按钮尺寸匹配:去掉按钮的height:100%,改用padding: 3px 8px来控制按钮高度,使其和输入框的高度(由padding:5px+边框撑起来)基本一致,同时保持按钮的点击区域合理。
  3. 复选框对齐优化:将复选框的vertical-align: -2px改为vertical-align: middle,和其他控件对齐基准统一。
  4. 单元格内边距:给td添加padding:4px,让控件之间有合适的间距,避免拥挤。

内容的提问来源于stack exchange,提问作者Baruch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:17:18