iPhoneJavaDev iPhoneJavaDev - 3 months ago 12
CSS Question

How to keep the divs aligned in bootstrap

I am using bootstrap to layout my page.
On a particular screen width, the

div
becomes misaligned because the title of one of the
div
is very long which occupies another line.

If the
div
next to it also have a long title (so both of them occupies 2 lines), then the
div
s will be properly aligned.

How should I configure the
div
s so that regardless whether the title is very long or short, the
div
s will still be aligned, that is for this screen
width
, I should see two
div
s side by side, instead of seeing the 3rd div moved to the right and the 4th div moved on the next line?

CODE

<div class="container">
<div class="row">
forloop {
<div class="col-md-3 col-xs-6" style="margin-bottom: 25px">
<img>
<h3>
</div>
}
</div>
</div>


enter image description here

Answer

2 options:

  • you can clear:left at each 3 item.

.row > div:nth-of-type(2n+1) {
  clear: left
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive" src="//placehold.it/300x300" />
      <h3>Very big text here to make 2 lines</h3>
    </div>
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive"src="//placehold.it/300x300" />
      <h3>text here</h3>
    </div>
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive"src="//placehold.it/300x300" />
      <h3>text here</h3>
    </div>
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive" src="//placehold.it/300x300" />
      <h3>text here</h3>
    </div>
  </div>
</div>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row">
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive" src="//placehold.it/300x300" />
      <h3>Very big text here to make 2 lines</h3>
    </div>
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive" src="//placehold.it/300x300" />
      <h3>text here</h3>
    </div>
    <div class="clearfix visible-xs-block"></div>
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive" src="//placehold.it/300x300" />
      <h3>text here</h3>
    </div>
    <div class="col-md-3 col-xs-6">
      <img class="img-responsive" src="//placehold.it/300x300" />
      <h3>text here</h3>
    </div>
  </div>
</div>