w3resource logo


How to cneter a div using Twitter Bootstrap 3

How to center a div using Twitter Bootstrap 3

Secondary Nav

Using Twitter Bootstrap's center-block helper class, which is available in Bootstrap 3.2, you may center a div.

center-block class contains following css code

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

It is evident from the code above that this class ensures that the block associated is displayed as a block-level element and it must have margins set as required to place it to the center.

Following code shows how to use center-block

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Center a Div in Twitter Bootstrap 3</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <style type="text/css">
    .center-block {
    width:250px;
    padding:10px;
    background-color:#eceadc;
    color:#ec8007
    }
    </style>
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="container">
    <div class="row">
    <div class="center-block">
    <p>Lorem ipsum dolor sit amet, animal postulant complectitur duo ei. Eros iracundia contentiones id cum. Utinam soleat apeirian nam cu. Unum labore principes no pro, dolor omnium quo eu, quod similique eu eum.</p>
<p>His ut alii populo putent, illud populo repudiare duo an. Wisi comprehensam te quo. Viris maluisset cu has, te dico utamur appareat pro, ex probo quidam interesset pri. Duo ad sensibus torquatos adolescens, sit minim labores nominati ne. Cu dolorum ocurreret mei, nam novum zril expetenda ne.</p>
    </div>
    </div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  </body>
</html>

View a live demo of the above.

Note that when an element is centered this way, teh element is placed directly within row class.



Join our Question Answer community to learn and share your programming knowledge.