首页 > 解决方案 > HTML表格第一列比第二列大很多

问题描述

所以我正在使用 javascript 在 html 中创建一个表。但是,每当我创建表时,第一列比第二列大得多,而第二列被极度压缩。

我试图让第一列被压缩,第二列成为更大的列,但由于某种原因它不想工作。

在此处输入图像描述

let rankings2 = [];

function generateTableHead(table, data) {
    let thead = table.createTHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);
      th.appendChild(text);
      row.appendChild(th);
      th.style.textAlign='center';
    }
  }


 function generateTable(table, data){
    for (let element of data) {
        let row = table.insertRow();
        for (key in element) {
          let cell = row.insertCell();
          let text = document.createTextNode(element[key]);
          cell.appendChild(text);
          cell.style.textAlign='center';
        }
      }
}

let HotSeat =  [{pos: "1", name:"Ben Shapiro's Wife"},
{pos: "2", name: "Illegal Bookies"},
  {pos: "3", name: "76ers"},
{pos: "4", name: "The Post Office",},
{pos: "5", name: "New Orleans"}];

let table2 = document.getElementById("HotSeatTable");
let data2 = Object.keys(HotSeat[0]);
generateTableHead(table2,data2);
generateTable(table2,HotSeat);

window.history.forward(1);
#HotSeat {
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  margin: 0 auto;
  width: 50%;
  box-shadow: 0 4px 6px 0 hsla(0, 0%, 0%, 0.2);
}

#HotSeat td,
#HotSeat th {
  border: 1px solid #ddd;
  text-align: left;
  width: 100%;
  padding: 20px;
}

#HotSeat tr:nth-child(even) {
  background-color: #f2f2f2;
}

#HotSeat tr:hover {
  background-color: #ddd;
}

#HotSeat th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  width: left;
  background-color: red;
  color: white;
}
<div id="HotSeat">
  <table id="HotSeatTable"></table>
</div>

这是我没有宽度时表格的样子:100% in td,th 在此处输入图像描述

标签: htmlcsshtml-table

解决方案


删除td选择器的宽度。这会导致您的列看起来歪斜。

然后添加width: 100%以使表格适合容器的宽度。

此外,我不确定您要对width: left财产做什么,所以我会删除它。与text-align: left样式表中的相同,您text-align: center在 JS 中动态设置,呈现左对齐无用,除非您真的希望它们左对齐。

#HotSeat {
  border-collapse: collapse;
  margin: 0 auto;
  width: 50%;
}

#HotSeatTable {
  width: 100%;
  text-align: center;
}

#HotSeat td,
#HotSeat th {
  border: 1px solid #ddd;
  padding: 20px;
}

#HotSeat th {
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: red;
  color: white;
}
<div id="HotSeat">
  <table id="HotSeatTable">
    <table id="HotSeatTable">
      <tr>
        <th>Pos</th>
        <th>Name</th>
      </tr>
      <tr>
        <td>1</td>
        <td>Ben Shapiro's Wife</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Illegal Bookies</td>
      </tr>
      <tr>
        <td>3</td>
        <td>76ers</td>
      </tr>
      <tr>
        <td>4</td>
        <td>The Post Office</td>
      </tr>
      <tr>
        <td>5</td>
        <td>New Orleans</td>
      </tr>
    </table>
</div>


推荐阅读