Table Cells: пустое пространство обернуть до достижения максимальной ширины, затем обернуть - PullRequest
0 голосов
/ 20 февраля 2020

В приведенном ниже примере я хочу, чтобы ячейки не переносили , пока они не достигли 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>

Ответы [ 3 ]

2 голосов
/ 10 апреля 2020

Это просто невозможно в css без javascript. Я сделал короткий скрипт, который проверяет, является ли ширина больше 119, и если да, то устанавливает стиль элементов на обычную упаковку так, как вы хотели.

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

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

 });

enter image description here


Полный код


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;
}
1 голос
/ 11 апреля 2020

Вы можете использовать это:

добавить word-wrap: break-word; и удалить white-space: nowrap;

Css:

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

th {
  background: #ccc;
  padding: 2px 5px;
  max-width: 120px;
  word-wrap: break-word;
}

Html код:

<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>

Результат:

enter image description here

0 голосов
/ 12 апреля 2020

Просто удалите

white-space: nowrap;

См. пример

The Result

...