html - 使每个 <td> 宽度适合其内容,而不是同一列中内容最长的 <td>

标签 html css width

我有一张表格,每行只有一个单元格。附加到每个单元格中的单词各不相同。有些短而有些长,但是每个单元格的宽度与内容最长的单元格的宽度相同。

是否可以在 css/html 中让每个单元格宽度适合其自己的内容,而不是内容最长的单元格?

$("#chatdisplay").append("<tr bgcolor='#ccffcc'><td><b>" + arr[i].date_time_sent + "</b><br/>" + arr[i].sender + ":" + "<br>" + arr[i].message + "<br></td></tr>");

$("#chatdisplay").append("&nbsp;");

CSS

table,th,td,tr {
  padding: 20px;
  border-radius: 20px;
  padding-top: 8px;
  padding-bottom: 8px;
}
table {
  overflow-y: scroll;
  height: 400px;
  width: 100%;
  display: block;
  background-color: #ffffff;
}

enter image description here

最佳答案

如果你真的想这样做 - 你可以,在 td 元素上使用 display: inline-block,然而这真的 < strong>不推荐,这不是执行此操作的方法。

您可以使用表格作为结构(即使您并不真正需要它),您也可以为此使用 div block 。

以下是所有 3 个选项的示例:

table,th,td,tr {
  padding: 20px;
  padding-top: 8px;
  padding-bottom: 8px;
}
table {
  overflow-y: scroll;
  width: 100%;
  display: block;
  background-color: #ffffff;
}
#tbl1 td {
  border-radius: 20px;
  background: #ccffcc;
  display: inline-block;
}
#tbl2 div.container {
  border-radius: 20px;
  background: #ccffcc;
  display: inline-block;
  padding: 8px 20px;
}
#tbl2 tr, #tbl2 td {
  padding: 0;
}
div.blocks div.container {
  padding: 4px 20px;
}
div.blocks div.container div.content {
  border-radius: 20px;
  background: #ccffcc;
  display: inline-block;
  padding: 8px 20px;
}
td with display: inline-block:<br />
<table id="tbl1">
  <tr>
    <td>This is some content</td>
  </tr><tr>
    <td>text</td>
  </tr><tr>
    <td>This is a cell with much more content</td>
  </tr>
</table>
<br />
div's insinde td<br />
<table id="tbl2">
  <tr>
    <td>
      <div class="container">This is some content</div>
    </td>
  </tr><tr>
    <td>
      <div class="container">text</div>
    </td>
  </tr><tr>
    <td>
      <div class="container">This is a cell with much more content</div>
    </td>
  </tr>
</table>

<br />
Div's only:<br />
<div class="blocks">
  <div class="container">
    <div class="content">This is some content</div>
  </div>
  <div class="container">
    <div class="content">text</div>
  </div>
  <div class="container">
    <div class="content">This is a cell with much more contentThis is a cell with much more contentThis is a cell with much more contentThis is a cell with much more contentThis is a cell with much more contentThis is a cell with much more contentThis is a cell with much more contentThis is a cell with much more contentThis is a cell with much more content</div>
  </div>
</div>

关于html - 使每个 <td> 宽度适合其内容,而不是同一列中内容最长的 <td>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39494351/

相关文章:

javascript - 上传多张图片到不同的div

javascript - 使用带有原始 javascript 的 offsetWidth 属性设置元素的宽度

html - 如何为调整窗口大小设置固定的最小宽度大小?

jquery - 使用 jQuery 计算 block 级元素中文本节点的宽度

php - 关闭并重新打开后继续填写 HTML 表单

javascript - 添加 HTML 文本框来修改 JS 数组项?要学习的最佳实践和资源?欢迎任何建议

html - CSS 背景渐变在溢出时重复

css - 固定边距和流体宽度占父级的 100%

html - 表格中的标签重叠

javascript - 如何在调整大小事件中获取 html5 视频宽度?