【问题标题】:Center the top th in a html table在 html 表格中居中顶部
【发布时间】:2019-10-31 04:26:12
【问题描述】:

我有一个 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>

【问题讨论】:

    标签: javascript html center


    【解决方案1】:

    似乎您尝试居中的第一行要么只包含一个&lt;td&gt;/&lt;th&gt;,要么只包含第一个&lt;td&gt;/&lt;th&gt; 中的文本,而下一个仍然为空。

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

    1. 确保第一行只有 1 个&lt;td&gt;/&lt;td&gt;
    2. 使用 colspan,例如:&lt;td colspan=2&gt;

    更多关于colspanhere

    【讨论】:

    • 虽然第一行只有一个 &lt;th&gt; ,但第二个解决方案实际上解决了我的问题。为什么?无论如何都非常感谢!
    猜你喜欢
    • 2012-08-22
    • 2015-09-30
    • 2012-12-13
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多