css 表格 thead th设置了自己的宽度 如果 实现tbody 中td宽度根据th 的宽度
时间: 2024-05-05 21:15:27 浏览: 17
可以使用CSS选择器和属性选择器来实现。
首先,为thead中的th设置宽度属性,例如:
```
thead th {
width: 100px;
}
```
然后,使用CSS选择器和属性选择器来选择tbody中的td元素,并将它们的宽度设置为与对应的th元素相同,例如:
```
tbody td:nth-of-type(1) { /* 第一列 */
width: 100px;
}
tbody td:nth-of-type(2) { /* 第二列 */
width: 100px;
}
/* ... */
```
使用nth-of-type选择器可以选择每一列的td元素,然后将它们的宽度设置为与对应的th元素相同。
相关问题
css 表格 实现tbody 中td宽度 根据thead th宽度自适应、
可以使用CSS中的表格布局属性来实现,具体如下:
1. 设置表格布局属性:
```
table {
table-layout: fixed;
width: 100%;
}
```
2. 设置thead中的th宽度:
```
thead th {
width: 25%;
}
```
3. 设置tbody中的td宽度:
```
tbody td {
word-wrap: break-word;
}
```
其中,word-wrap: break-word;属性用于自动换行,防止内容溢出。
这样,tbody中的每个td宽度就会根据thead中对应的th宽度进行自适应了。完整代码如下:
```
table {
table-layout: fixed;
width: 100%;
}
thead th {
width: 25%;
}
tbody td {
word-wrap: break-word;
}
```
css 表格 实现td 根据 th宽度
可以使用CSS中的属性选择器和伪元素来实现。
首先,给每个th设置一个data属性,记录其宽度值,如下所示:
```html
<table>
<thead>
<tr>
<th data-width="100">Name</th>
<th data-width="150">Age</th>
<th data-width="200">City</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
<td>Los Angeles</td>
</tr>
</tbody>
</table>
```
然后,使用CSS属性选择器选择每个td,并利用伪元素:before来插入一个空的占位元素,宽度设置为对应th的宽度值,代码如下:
```css
table {
width: 100%;
border-collapse: collapse;
}
th {
background-color: #ddd;
font-weight: bold;
text-align: left;
padding: 10px;
}
td {
padding: 10px;
}
td:before {
content: "";
display: inline-block;
width: attr(data-width px, 0); /* 使用attr()函数获取对应th的data-width属性值 */
vertical-align: middle;
}
```
这样,每个td就会在其前面插入一个宽度为对应th宽度值的空元素,从而实现了td宽度根据th的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)