How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3.
Please see the starter fiddle.
<body class="container">
<div class="col-lg-1 col-offset-6 centered">
<img data-src="holder.js/100x100" alt="" />
</div>
</body>
So, I want a div
, with a class centered
to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with size of one column centered within the container (12 columns).
I am also not sure the above approach is good enough as the intention is not to offset the div
by half. I do not need free spaces outside the div
and the contents of the div
shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width == one column).
Method 1:
Method 2:
CSS
Bootstrap Tips, examples and tools: OnAirCode
The preferred method of centering columns is to use "offsets" (ie:
col-md-offset-3
)Bootstrap 3.x centering examples
For centering elements, there is a
center-block
helper class.You can also use
text-center
to center text (and inline elements).Demo: http://bootply.com/91632
EDIT - As mentioned in the comments,
center-block
works on column contents anddisplay:block
elements, but won't work on the column itself (col-*
divs) because Bootstrap usesfloat
.Update 2018
Now with Bootstrap 4, the centering methods have changed..
text-center
is still used fordisplay:inline
elementsmx-auto
replacescenter-block
to centerdisplay:block
elementsoffset-*
ormx-auto
can be used to center grid columnsmx-auto
(auto x-axis margins) will centerdisplay:block
ordisplay:flex
elements that have a defined width, (%
,vw
,px
, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.Demo Bootstrap 4 Horizontal Centering
For vertical centering in BS4 see https://stackoverflow.com/a/41464397/171456
Don't forget to add
!important
. Then you can be sure that element really will be in the center:Another approach of offsetting is to have two empty rows, for example:
My approach to center columns is to use
display: inline-block
for columns andtext-align: center
for the container parent.You just have to add the CSS class 'centered' to the
row
.HTML:
CSS:
JSfiddle: http://jsfiddle.net/steyffi/ug4fzcjd/
As koala_dev used in his approach 1, I would prefer the offset method instead of center-block or margins which has limited usage, but as he mentioned:
This can be solved using the following approach for odd columns.