我有一张表格,每行只有一个单元格。附加到每个单元格中的单词各不相同。有些短而有些长,但是每个单元格的宽度与内容最长的单元格的宽度相同。
是否可以在 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(" ");
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;
}
最佳答案
如果你真的想这样做 - 你可以,在 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/