在表格中以 Bootstrap 为中心

由于某种原因,表中的文本仍然没有居中。为什么?如何在表中居中显示文本?

让它真正清楚: 例如,我想“罗兰”坐在中间的四个“1”。

@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');
table,
thead,
tr,
tbody,
th,
td {
text-align: center;
}
<table class="table">
<thead>
<tr>
<th>1</th>
<th>1</th>
<th>1</th>
<th>1</th>
<th>2</th>
<th>2</th>
<th>2</th>
<th>2</th>
<th>3</th>
<th>3</th>
<th>3</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4">Lorem</td>
<td colspan="4">ipsum</td>
<td colspan="4">dolor</td>
</tr>
</tbody>
</table>

JSFiddle

450012 次浏览

.table td的文本对齐设置为左,而不是居中。

添加这个应该会使你的所有 td都居中:

.table td {
text-align: center;
}

@import url('https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css');
table,
thead,
tr,
tbody,
th,
td {
text-align: center;
}


.table td {
text-align: center;
}
<table class="table">
<thead>
<tr>
<th>1</th>
<th>1</th>
<th>1</th>
<th>1</th>
<th>2</th>
<th>2</th>
<th>2</th>
<th>2</th>
<th>3</th>
<th>3</th>
<th>3</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4">Lorem</td>
<td colspan="4">ipsum</td>
<td colspan="4">dolor</td>
</tr>
</tbody>
</table>

更新 JSFIDDLE

<td class="text-center">

在 bootstrap.css 中修复. text-center:

.text-center {
text-align: center !important;
}

你可以在不改变 css 的情况下,通过在单元格中添加一个 div,其中包含一个“ text-center”类来实现 td 的对齐:

    <td>
<div class="text-center">
My centered text
</div>
</td>

Bootstrap 的一个主要特性是它减轻了对! important 标记的使用。 使用上述答案将会破坏目的。您可以通过修改您自己的 css 文件中的类并在包含 boostrap css 之后链接它来轻松地自定义 bootstrap。

补充:

<p class="text-center"> Your text here... </p>

在 Bootstrap 3(3.0.3)中,向 td元素添加 "text-center"类可以立竿见影。

也就是说,下面的中心 some text在一个表单元格中:

<td class="text-center">some text</td>

我也有同样的问题,不使用 !important的更好的解决方法是在 CSS 中定义以下内容:

table th.text-center, table td.text-center {
text-align: center;
}

这样,text-center类的特定性就可以在表中正确工作。

如果只有一次,则不应更改样式表。 只要编辑特定的 td:

<td style="text-align: center;">

干杯

我认为最适合 HTML 和 CSS 的快速和干净的 mod 组合是:

<table class="table text-center">
<thead>
<tr>
<th class="text-center">Uno</th>
<th class="text-center">Due</th>
<th class="text-center">Tre</th>
<th class="text-center">Quattro</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>

关闭 <table> init 标记,然后在需要的地方复制:) 我希望它能派上用场 祝你愉快 堆栈溢出

附注: Bootstrap v3.2.0

只要给周围的 <tr>一个自定义类,比如:

<tr class="custom_centered">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>

并让 css 只选择 <td>,这些 <td>位于自定义类的 <tr>中。

tr.custom_centered td {
text-align: center;
}

像这样,您不会冒险覆盖其他表,甚至不会覆盖引导程序基类(就像我的一些前辈建议的那样)。