September 15, 2013

How to have a centered bootstrap layout

User2594008’s Question:

I need to create a responsive layout, and I have used bootstrap before but I have never actually attempted this. Making full width designs is plenty easy, but I want a two column layout that would say.. have a max width of 900px together.

The example of what I am trying to do can actually be seen right here on stackoverflow. There are two columns to this site, but both columns are centered on the page right now with space to the left and right. I just need that (and responsive as well for smaller screens).

Assuming your container has an id of container you can center it by giving auto left and right margin like:

#container { 
   margin: 0 auto;
}

The width of a default bootstrap grid is 960px and is already centered by default. You only have to assign a class called container like

<div class="container">
     <!-- The begin your row -->
     <div class="row">
          <div class="span8">
               Demo right part of stackoverflow
          </div>
          <div class="span4">
               Demo left part of stackoverflow         
          </div>
     </div>
</div>
April 29, 2012

Using jQuery for vertical and horizontal centering

Question by JamesCharless

I’m using jQuery to horizontally center a div element that doesn’t have a default width. I’m using the following code, but it’s not working. if anyone could help me to understand why, it’d be very helpful. PS, I the height has a default height of 20, so that’s where the -10px comes from.

var w = ($(".notec").width() + 51) / 2;
$(".buttons").css("margin", "-10px 0 0 -" + w + "px");

Answer by Starx

Centering with respect to .notec. Width is not needed if the element is displaying as block element.

var h = ($(".notec").height() - $(".buttons").height()) / 2;
$(".buttons").css("margin", h+"px auto 0 auto');
...

Please fill the form - I will response as fast as I can!