如何防止表格单元格中的文本换行

pka*_*ing 272 html css

有谁知道如何防止表格单元格中的文本被包装?这是一个表的标题,标题比它下面的数据长很多,但我需要它只显示一行.如果色谱柱很宽,也没关系.

我(简化)表的HTML如下所示:

<table>
  <thead>
    <tr>
      <th>
        <div>Really long column heading</div>
      </th>
      <th>
        <div>Really long column heading</div>
      </th>
      <th>
        <div>Really long column heading</div>
      </th>
      <th>
        <div>Really long column heading</div>
      </th>
      <th>
        <div>Really long column heading</div>
      </th>
      <th>
        <div>Really long column heading</div>
      </th>
      <th>
        <div>Really long column heading</div>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <div>data</div>
      </td>
      <td>
        <div>data</div>
      </td>
      <td>
        <div>data</div>
      </td>
      <td>
        <div>data</div>
      </td>
      <td>
        <div>data</div>
      </td>
      <td>
        <div>data</div>
      </td>
      <td>
        <div>data</div>
      </td>
    </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

标题本身包含在th标记内的div中,原因与页面上的javascript有关.

桌子出来的标题包裹在多条线上.这似乎只发生在表足够宽时,因为浏览器试图避免水平滚动.但就我而言,我想要水平滚动.

有任何想法吗?

Owe*_*wen 457

看看这个white-space属性,使用如下:

th {
    white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)

这将强制<th>显示在一行上的内容.

从链接页面,以下是各种选项white-space:

normal
此值指示用户代理折叠空白序列,并根据需要断行以填充行框.

pre
此值可防止用户代理折叠空白序列.仅在保留的换行符处断行.

nowrap
此值会折叠白色空间,与"normal"相同,但会抑制文本中的换行符.

pre-wrap
此值可防止用户代理折叠空白序列.在保留的换行符处打破行,并根据需要填充行框.

pre-line
此值指示用户代理折叠空白序列.在保留的换行符处打破行,并根据需要填充行框.

  • `table`元素必须有`table-layout:fixed;`才能使它工作. (15认同)
  • 不适用于同一单元格中的输入字段和按钮.随机放在下面. (8认同)

Gra*_*ner 59

<th nowrap="nowrap">
Run Code Online (Sandbox Code Playgroud)

要么

<th style="white-space:nowrap;">
Run Code Online (Sandbox Code Playgroud)

要么

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`nowrap`已被弃用.https://www.w3.org/TR/html401/struct/tables.html#h-11.2.6.请改用样式表. (6认同)
  • @wisbucky 如何“使用样式表”? (2认同)

Ser*_*nko 20

至少有两种方法可以做到:

在"td"标记内使用nowrap属性:

<th nowrap="nowrap">Really long column heading</th>
Run Code Online (Sandbox Code Playgroud)

在你的单词之间使用不可破坏的空格:

<th>Really&nbsp;long&nbsp;column&nbsp;heading</th>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`nowrap`已被弃用.https://www.w3.org/TR/html401/struct/tables.html#h-11.2.6.请改用样式表. (6认同)

css*_*hus 5

我遇到这个问题,需要防止在连字符处换行。

这是我的方法:

<td><nobr>Table Text</nobr></td>
Run Code Online (Sandbox Code Playgroud)

参考:

如何在所有浏览器上防止连字符出现换行

  • 值得注意的是,“nobr”标签是非标准的,正如本答案中链接的接受答案中所指出的:http://stackoverflow.com/a/8755071/4257 (2认同)