一个<table>的一行有很多列,这些列有一些宽度的要求,但是给td加width加不上,td会随着表格的整体宽度收缩,唯一可行的方法是给td里面加个<div>,给div设置width就可以加上,示例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>table设置宽度</title>
</head>
<style>
/* .table-waibox{
width: 500px;
height: 500px;
border:1px solid red;
overflow: scroll;
} */
.table1{
width: 100%;
border-collapse: collapse;
}
.table1 tr td,.table1 tr th{
border:1px solid #ddd;
}
.tdwidth{
width: 200px;/*宽度都设为200px*/
word-wrap: break-word; /* 可选,处理长文本 */
text-align: center;/*标题文本居中*/
}
/* 如果有特殊的宽度,就在后边多设置一个class名字,在下边单独写css宽度 */
.tw02{
width: 500px;
}
</style>
<body>
<div class="table-waibox">
<table class="table1">
<thead>
<tr>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth tw02">标题我是一个很长很长的标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
<th><div class="tdwidth">标题</div></th>
</tr>
</thead>
<tbody>
<tr>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
</tr>
<tr>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
</tr>
<tr>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<td>内容</td>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
<th>表头</th>
</tr>
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
</script>
</html>