How to center a div with Bootstrap2?

巧了我就是萌 提交于 2019-11-27 17:14:07
csturtz

besides shrinking the div itself to the size you want, by reducing span size like so... class="span6 offset3", class="span4 offset4", etc... something as simple as style="text-align: center" on the div could have the effect you're looking for

you can't use span7 with any set offset and get the span centered on the page (Because total spans = 12)

Zuhaib Ali

Bootstrap's spans are floated to the left. All it takes to center them is override this behavior. I do this by adding this to my stylesheet:

.center {
     float: none;
     margin-left: auto;
     margin-right: auto;
}

If you have this class defined, just add it to the span and you're good to go.

<div class="span7 center"> box </div>

Note that this custom center class must be defined after the bootstrap css. You could use !important but that isn't recommended.

Casey

Bootstrap3 has the .center-block class that you can use. It is defined as

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

Documentation here.

If you want to go full-bootstrap (and not the auto left/right way) you need a pattern that will fit within 12 columns e.g. 2 blanks, 8 content, 2 blanks. That's what this setup will do. It only covers the -md- variants, I tend to snap it to full size for small by adding col-xs-12

<div class="container">
  <div class="col-md-8 col-md-offset-2">
     box
  </div>
</div>

Sounds like you just wanted to center align a single container. The bootstrap framework might be overcomplicating that one example, you could have just had a standalone div with your own styling, something like:

<div class="login-container">
  <!-- Your Login Form -->
</div>

and style:

.login-container {
  margin: 0 auto;
  width: 400px; /* Whatever exact width you are looking for (not bound by preset bootstrap widths) */
}

That should work fine if you are nested somewhere within a bootstrap .container div.

add the class centercontents

/** Center the contents of the element **/
.centercontents {
    text-align: center !important;
}
jakson

@ZuhaibAli code kind of work for me but I changed it a little bit:

I created a new class in css

.center {
     float: none;
     margin-left: auto;
     margin-right: auto;
}

then the div become

<div class="center col-md-6"></div>

I added col-md-6 for the width of the div itself which in this situation meant the div is half the size, there are 1 -12 col md in bootstrap.

Follow this guidance https://getbootstrap.com/docs/3.3/css/

Use .center-block

.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!