I'm currently creating a web page with Bootstrap and I'm using columns. My page looks like that:
I'd like to center the last column (in the second row) but the page is dynamic and I don't know how many containers there are.
I found this two solutions on Google:
1) Add this to my css:
.col-centered{
float: none;
margin: 0 auto;
}
2) Add this to the class tag attribute
col-lg-offset-4
But both solutions look like this:
That is not what i want. I want it to look like this:
How can i achieve this?
You need to add the last block of text into a different row and change the "col-md-4" to "col-md-12".
Bootstrap's columns are floating by default with css
float
property. Withfloat
we can't middle align columns. However withdisplay: inline-block
we can. All we need is to removefloat
from styles of columns and change them toinline-block
withvertical-align: middle
and you will get what you want. But don't forget to remove extra space that comes withinline-block
.Here is the trick.
Note: Setting font-size: 0; letter-spacing: -4px on parent and applying parent's font-size: 14px; letter-spacing: 0 back on child elements will remove white space that comes with inline-block.
Bootstrap has built-in functionality to achieve the layout you are after, without the introduction of additional CSS rules. Simply use the
.col-md-offset-*
class:Your layout would end up looking similar to this:
EDIT #1: For your requirement of not knowing how many columns you will be fetching from your database for the second row, another option would be to use a conditional during the output of the HTML to also output a
.col-md-offset-4
class if the modulo of the number of items in your collection divided by the number of columns is equal to 1, or proceed as usual otherwise. In ASP.NET with Razor, this would look something like this (the example below is kept simple on purpose to demonstrate the proposed logic, it can be refactored to it's own HTML helper class, accounting for other column sizes as well):EDIT #2: Looks like I misread your requirement. For 1 left-over column, this solution will suffice. For more, I would go with @Muhammad's answer.