在html表格的顶部居中

时间:2019-06-17 14:43:42

标签: javascript html center

我有一个html表,该表的内容是使用Javascript从API收集的。我试图将文本居中于html表的第一行(该表位于模式窗口中),但它不会居中。它总是停留在左侧。

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>

Photo:

1 个答案:

答案 0 :(得分:4)

似乎您要居中的第一行要么只包含一个<td> / <th>,要么只包含文本的第一行<td> / <th> ,而下一个保持空白。

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

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

有关colspan here

的更多信息