在Twitter Bootstrap中将表格中的文本居中

问题描述 投票:96回答:10

出于某种原因,表格内的文字仍然没有居中。为什么?如何将文本置于表格中心?

为了使它真正清晰:例如,我希望“Lorem”坐在四个“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

twitter-bootstrap
10个回答
132
投票

.table td的text-align设置为left,而不是center:

添加它应该集中在它:

.table td {
   text-align: center;   
}

@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.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>

Updated JSFIDDLE


0
投票

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

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

并让css只选择与你的自定义类在<td>内的<tr>s。

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

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


151
投票

在Bootstrap 3(3.0.3)中,将"text-center"类添加到td元素中,开箱即用。

即,以下中心some text在表格单元格中:

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

29
投票

我认为对于快速和干净的mod,html和Css的最佳组合是:

<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标签,然后复制到你想要的地方:)我希望它可以有用有一个美好的一天w stackoverflow

附: Bootstrap v3.2.0


26
投票

你可以通过在单元格中添加一个带有“text-center”类的div来使td对齐而不改变css:

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

11
投票
<td class="text-center">

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

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

5
投票

我有同样的问题和更好的解决方法而不使用!important在我的css中定义了以下内容:

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

这样,文本中心类的特殊性在表中正常工作


4
投票

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


4
投票

加:

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

4
投票

我只有一次,你不应该改变你的样式表。只需编辑该特定的td

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

干杯

© www.soinside.com 2019 - 2024. All rights reserved.