Bootstrap has built-in functions to achieve the layout you use without introducing additional CSS rules. Just use the .col-md-offset-* :
Move the columns to the right using the .col-md-offset-* . These classes increase the left margin of the column by * columns. For example, .col-md-offset-4 moves .col-md-4 into four columns.
Your layout will look something like this:
.show-grid { margin-bottom: 15px; } .your-custom-div { height: 50px; background-color: green; color: white; text-align: center; }
<!DOCTYPE html> <html lang="en"> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div class="container"> <div class="row show-grid"> <div class="col-md-4"> <div class="your-custom-div"> .col-md-4 </div> </div> <div class="col-md-4"> <div class="your-custom-div"> .col-md-4 </div> </div> <div class="col-md-4"> <div class="your-custom-div"> .col-md-4 </div> </div> <div class="clearfix visible-md"></div> </div> <div class="row show-grid"> <div class="col-md-4 col-md-offset-4"> <div class="your-custom-div"> .col-md-4 .col-md-offset-4 </div> </div> <div class="clearfix visible-md"></div> </div> </div> </body> </html>
EDIT # 1: for your requirement not to know how many columns you select from your database for the second row, another option would be to use a conditional expression during HTML output to output the .col-md-offset-4 class if modulo the number of items in your collection divided by the number of columns is 1 or, as usual, otherwise. In ASP.NET with Razor, it would look something like this (the example below is just simple to demonstrate the proposed logic, it can be reorganized into its own HTML helper class, taking into account other column sizes):
@{ bool lastItemShouldBeCentered = Foo.Count % 3 == 1; for (int i = 0; i < Foo.Count; i++) { bool isLastItem = i == Foo.Count - 1; if (isLastItem && lastItemShouldBeCentered) { <div class="col-md-4 col-md-offset-4"> // Foo[i] content here </div> } else { <div class="col-md-4"> // Foo[i] content here </div> } } }
EDIT No. 2: Looks like I misunderstood your requirement. For 1 left column this solution will be enough. Moreover, I would go with @Muhammad's answer.
source share