html - 如何根据内容自动调整表格 td 宽度

标签 html css html-table

首先请试着看看这个jsFiddle ,正如您所看到的,我有一个包含很多列的表格,我唯一的问题是如何让所有 td 根据其中文本的长度调整其宽度而不换行?

这是我的代码:

.content {
  width: 1100px;
  height: 200px;
  background: #fdfdfd;
  margin: 0px auto;
  position: relative;
  top: 40px;
  border: 1px solid #aaaaaa;
}

.content .content-header {
  width: 100%;
  height: 40px;
  background-color: #aaa;
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#cccccc));
  background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
  background-image: linear-gradient(to bottom, #eeeeee, #cccccc);
  border-bottom: 1px solid #aaaaaa;
}

.content-loader {
  overflow: scroll;
}

.content-loader table {
  width: auto;
  background: #aaa;
}

.content-loader table tr {
  background: #eee;
}

.content-loader table tr td {}
<div class="content">
  <div class="content-header">

  </div>
  <div class="content-loader">
    <table>
      <tbody>
        <tr>
          <td>First Name</td>
          <td>Last Name</td>
          <td>Gender</td>
          <td>Birth Date</td>
          <td>Address</td>
          <td>Zip Code</td>
          <td>Nationality</td>
          <td>Contact Number</td>
          <td>Email</td>
          <td>Username</td>
          <td>Course</td>
          <td>Year</td>
          <td>ID Number</td>
          <td>Subjects</td>
          <td>Other Fields</td>
          <td>Other Fields</td>
          <td>Other Fields</td>
          <td>Other Fields</td>
          <td>Other Fields</td>
          <td>Other Fields</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

有人可以帮我解决这个问题吗?或者,如果这里已经有人问过,请告诉我链接。

最佳答案

删除所有使用 CSS 设置的宽度,并将空白设置为 nowrap,如下所示:

.content-loader tr td {
    white-space: nowrap;
}

如果您希望字段完整显示而不显得奇怪,我还会从容器中删除固定宽度(或将 overflow-x: scroll 添加到容器中)...

在这里查看更多信息:http://www.w3schools.com/cssref/pr_text_white-space.asp

关于html - 如何根据内容自动调整表格 td 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632363/

相关文章:

html - 如何将图像添加到 <p> 并在 UIWebView 中使用?

html - CSS 动画后的文本 "nudging"本身

javascript - Jquery循环遍历表中的所有行,没有第一行

jquery - 如何使用此 jquery 脚本添加表行?

javascript - 如果单词出现在 div 中则计数器

html - 当屏幕达到一定宽度(像素)时显示图像

html - 网站标题出现奇怪的白色 1 像素线

javascript - 根据循环横幅中的行数应用样式以跨度

html - 如何让 CSS3 渐变跨越整个页面的高度,而不仅仅是视口(viewport)?

html - 响应式 CSS 表格