首页 > 解决方案 > 根据屏幕宽度在表格内换行

问题描述

考虑到屏幕宽度调整大小,我想在表格中包含单行文本。表格占据屏幕宽度的 100%,我只想在调整窗口大小后将文本换行(如果超出内容宽度,则用省略号换行)。我只能在以像素为单位指定固定宽度时实现文本换行。JSFiddle:https ://jsfiddle.net/4vo7p58c/5

问题是没有固定width元素td,它不会换行文本,一旦我水平调整窗口大小,行会分成两行而不是换行文本以适应屏幕宽度

标签: cssresponsive

解决方案


你的代码几乎就在那里,

td是默认table-cell元素,通常不同于inline-blockor block

如果你想使用ellipsisvalue 那么你应该有一个宽度,td这将确保内容保持溢出并display:block/inline-block;为你的原因使用,它适用于两者。

table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid red;
  table-layout: fixed;
}

th {
  text-align: left;
  border-bottom: 1pt solid #4C4C4C;
  border-right: 1pt solid #4C4C4C;
  padding: 8px;
  width: 20%;
}

td {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  width: 100%;
  border: 1px solid #000000;
  word-wrap: break-word;
}
<div class="External">
  <table>
    <tr>
      <th>First Element</th>
      <td>Text</td>
    </tr>
    <tr>
      <th>Second Element</th>
      <td>Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum</td>
    </tr>
    <tr>
      <th>Third Element</th>
      <td>Text</td>
    </tr>
    <tr>
      <th>Fourth Element</th>
      <td>Text</td>
    </tr>
  </table>
</div>


推荐阅读