如何使表格td tr根据文本长度自动宽度

How to make table td tr auto width based on text length?

本文关键字:文本 表格 何使 td tr      更新时间:2023-09-26

我有一个宽度为100%的表,如何根据文本长度自动宽度设置TD和TR?我使用了宽度:auto,但它不起作用。这是我的代码:

.hoverTable {
  width: 100%;
  border-collapse: collapse;
}
.hoverTable td {
  padding: 7px;
  border: #4e95f4 1px solid;
}
/* Define the default color for all the table rows */
.hoverTable tr {
  background: #b8d1f3;
}
/* Define the hover highlight color for the table row */
.hoverTable tr:hover {
  background-color: #ffff99;
}
.hoverTable th {
  background: #b8d1f3;
}
<table class="hoverTable">
  <tr>
    <th colspan="3">Some Text here</th>
  </tr>
  <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
    <td>This is text length example and text</td>
    <td>Item 1B</td>
    <td>Item 1C</td>
  </tr>
  <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
    <td>Item 2A</td>
    <td>Item 2B</td>
    <td>Item 2C</td>
  </tr>
  <th colspan="3" class="width: 100%;">Some Text here</th>
  <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
    <td>Item 3A</td>
    <td>Item 3B</td>
    <td>Item 3C</td>
  </tr>
  <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
    <td>Item 4A</td>
    <td>Item 4B</td>
    <td>Item 4C</td>
  </tr>
  <tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
    <td>Item 5A</td>
    <td>Item 5B</td>
    <td>Item 5C</td>
  </tr>
</table>

正如您在中看到的,这是文本长度示例,文本宽度不是基于文本长度的,我如何根据文本长度设置宽度。。

我的意思是基于文本长度的自动宽度?

感谢

使用以下内容:

.hoverTable {
    border-collapse: collapse;
}

所以只要移除width: 100%;,它就会工作。现在将动态呈现该表。

Fiddle:单击