首页 > 解决方案 > 表格单元格:空白 nowrap 直到满足最大宽度,然后换行

问题描述

在下面的示例中,我希望单元格到达max-width. 这仍然会导致表溢出,这我想要的行为。

main {
  max-width: 600px;
  overflow: hidden;
}

th {
  background: #ccc;
  padding: 2px 5px;
  white-space: nowrap;
  max-width: 120px;
}
<main>
  <table>
  <tr>
    <th>One</th>
    <th>One Two</th>
    <th>One Two Three</th>
    <th>Four</th>
    <th>Five</th>
    <th>Six</th>
    <th>Seven</th>
    <th>Seven Eight</th>
    <th>Seven Eight Nine</th>
    <th>Seven Eight Nine Ten</th>
  </tr>
  </table>
</main>

标签: csshtml-tablewidthnowrap

解决方案


这在没有javascript的 css 中根本不可能。我制作了一个简短的脚本来检查宽度是否大于 119,如果是,则根据需要将该元素样式设置为正常环绕。

 var a = document.querySelectorAll("th");

 a.forEach((a) => {
   if(a.offsetWidth > 119) {
     a.style.whiteSpace = "normal";
   }else {
     console.log(a.offsetWidth);
   }

 });

在此处输入图像描述


完整代码


html

<main>
  <table>
  <tr>
    <th class="t">One</th>
    <th>One Two</th>
    <th>One Two Three</th>
    <th>Four</th>
    <th>Five</th>
    <th>Six</th>
    <th>Seven</th>
    <th>Seven Eight</th>
    <th>Seven Eight Nine</th>
    <th>Seven Eight Nine Ten</th>
  </tr>
  </table>
</main>

<script type="text/javascript">

     var a = document.querySelectorAll("th");

     a.forEach((a) => {
       if(a.offsetWidth > 119) {
         a.style.whiteSpace = "normal";
       }else {
         console.log(a.offsetWidth);
       }

     });

</script>

css

main {
  max-width: 600px;
  overflow: hidden;
}

th {
  background: #ccc;
  padding: 2px 5px;
  white-space: nowrap;
  max-width: 120px;
}

推荐阅读