Bootstrap如何让div居中对齐

26

我正在尝试让页面底部的一些按钮居中显示,但出于某些原因似乎无法实现。

<div class="footer">
  <div class="container">   
    <div class="navbar-text pull-left">
      <p> Hello there </p>
    </div>
        <div class="Button" align="center">  
            <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
            <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
        </div>
    <div class="navbar-text pull-right">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div> 

我不确定我是否需要使用CSS让它居中,还是仅使用对齐方式,但没有任何效果。


它在这里运行良好:https://jsfiddle.net/qmt26y5d/。 也许你有一些与其干扰的CSS?需要提供更多的代码。 - Keith Anderson
对我有效 https://jsfiddle.net/7oe5kh9L/ - Adam Buchanan Smith
我不确定为什么右侧的字体也会稍微下降,有没有办法让它们在同一行上。 - CamelHump
未来使用 Bootstrap 4 或 Bootstrap 5 的读者请参考:Bootstrap 垂直和水平居中对齐 - Carol Skelly
2个回答

32
在Bootstrap中,您可以使用.text-center来使文本居中对齐。同时,在您的代码中添加.row.col-md-*align=已被弃用。为演示添加了.col-xs-*

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>

2017年10月更新

如果您正在阅读此内容并想要使用Bootstrap的新版本(测试版),您可以更简单地使用Bootstrap的Flexbox工具类来完成上述操作。

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>


太好了,你知道右侧的字体为什么会下降吗?有没有办法让它们都在同一行上? - CamelHump

31

当我需要让元素居中时,我使用Bootstrap的text-center类:

<div class="text-center">居中内容在此</div>


3
就像这样:<div class="text-center">居中的内容放在这里</div> - Dimitar Popov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接