将顶部居中 html table

Center the top th in a html table

我有一个 html table,其内容是使用 Javascript 从 API 收集的。我试图将我的 html table(table 处于模态 window)顶行的文本居中,但它不会居中。它总是在左边。

if (data.foods) {
  //here is the top row->  var div = "<tr><th>" + data.foods[0].food.desc.name + "</th></tr>" + "<tr><td>Nutrition Facts</th><td>per 100gr</td></tr>";
  data.foods[0].food.nutrients.map(nutrients => {
        let tableList = "<tr><td>" + nutrients.name + ": " + "</td><td>" + nutrients.value + nutrients.unit + "</td></tr>";
        div += tableList;
        nutrientData.innerHTML = div;
        //modal 
        var modal = document.getElementById("modal");
        var span = document.getElementsByClassName("close")[0];
        modal.style.display = "block";
        span.onclick = function() {
          modal.style.display = "none";
        }
/* modal content-box */

.modal-content {
  background-color: #fefefe;
  margin: 10% auto;
  padding: 10px;
  border: 1px solid #888;
  width: 20vw;
  height: 70%;
  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
  text-align: center;
  overflow: scroll;
}

.modal-content table {
  table-layout: fixed;
  border-spacing: 1;
  border-collapse: collapse;
  text-align: center;
  height: 100%;
  width: 100%;
  border: solid 2px red;
  line-height: 1.35;
}

.modal-content tr,
.modal-content td {
  border: solid 0.5px black;
}
<div class="modal-content">
  <span class="close">&times;</span>
  <table id="nutrientData">
    <!--api nutrient data here-->
  </table>
</div>

您尝试居中的第一行似乎只包含一个 <td>/<th>,或者仅包含第一个 <td>/[=11] 中的文本=],而下一个仍然是空的。

无论哪种情况,您都可以执行以下操作:

  1. 确保第一行只有 1 <td>/<td>
  2. 使用 colspan,例如:<td colspan=2>

更多关于 colspan here