Bootstrap
目前已经发布了4.1.x
正式版本,相比起Bootstrap 3
来说,简直是一个质的飞跃,在这里强烈建议还在使用旧版本的朋友升级到4.1.x
。
好了,今天我们要来讲解一下,在Bootstrap 4
(以下简称BS4
)中如何自定义表格的列宽度。
我们的示例中使用的是row
,col
等一系列类名(class
)来完成表格宽度的自定义,当然也可以直接自定义css
,不过这就不属于我们的讨论范畴了。
首先我们建立一张只包含了颜色样式的表格:
<div class="container mt-5">
<!-- First table without widths classes -->
<table class="table table-bordered text-white">
<thead>
<tr class="bg-primary">
<th>#</th>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
</thead>
<tbody>
<tr class="bg-dark">
<th>1</th>
<td>This is a remarkably long phrase.</td>
<td>Javascript</td>
<td>Python</td>
</tr>
<tr class="bg-secondary">
<th>2</th>
<td>Having fun with Bootstrap 4!</td>
<td>CSS</td>
<td>Bootstrap</td>
</tr>
<tr class="bg-success">
<th>3</th>
<td>PHP</td>
<td>npm</td>
<td>nodejs</td>
</tr>
</tbody>
</table>
<!-- End first table -->
</div>
可以看到,表格的列都是不同宽度。
那么我们来演示一下如何将表格所有列都设置成一样宽度。
我们建立第二张表格,在表格里添加一些row
,col
等类名:
<div class="container mt-5">
<!-- Second table with widths classes -->
<table class="table table-bordered row mx-0 text-white">
<thead class="w-100">
<tr class="row mx-0 bg-primary">
<th class="col-3">#</th>
<th class="col-3">First</th>
<th class="col-3">Last</th>
<th class="col-3">Handle</th>
</tr>
</thead>
<tbody class="w-100">
<tr class="row mx-0 bg-dark">
<th class="col-3">1</th>
<td class="col-3">This is a remarkably long phrase.</td>
<td class="col-3">Javascript</td>
<td class="col-3">Python</td>
</tr>
<tr class="row mx-0 bg-secondary">
<th class="col-3">2</th>
<td class="col-3">Having fun with Bootstrap 4!</td>
<td class="col-3">CSS</td>
<td class="col-3">Bootstrap</td>
</tr>
<tr class="row mx-0 bg-success">
<th class="col-3">3</th>
<td class="col-3">PHP</td>
<td class="col-3">npm</td>
<td class="col-3">nodejs</td>
</tr>
</tbody>
</table>
<!-- End second table -->
</div>
可以看到,我们给table
及tr
加上了row
,thead
及tbody
使用了w-100
让其占满整个表格长度,然后th
及td
全部使用了col-3
使每列宽度一致。
我们来看一下两张表格比对图:
注意,如果你需要不同的列宽度,可以根据你的需求相应更改
col-3
为其他长度,例如col-4
,但是需要保证所有列长度相加正好为col-12
的长度,并且需要注意,th
和对应td
需要相同的类才能保持宽度一致。
另外,通常在使用
row
的时候记得加上mx-0
,否则会出现margin
诡异的问题,大家可以自己测试。
由于中文字体的
padding
问题,如果遇到单行显示不下的情况,可以在适当的单元中修改默认的padding
(例如加上px-0
)
好了,今天就讲解到这里,有问题欢迎指正与交流。