Beppe
Beppe

Reputation: 207

Method to show responsive divs side by side to fit whole space with margins in between them

I'm struggling to find a reliable solution to show any number of divs side by side to fit the whole space. They also need to have same height and size despite their content. The divs need to have some margin to separate one another. I cannot use Flex as the page I'm working on needs to be IE9 compatible. Hence, I'm relying on inline-block, floats and table methods.

Can you suggest anything?

Here is the HTML of what I've tried and the fiddle link for the full example --> https://jsfiddle.net/crvu1oc9/

<div class="cards-list">
   <div class="card">
      <div class="card__image-box">
        <img class="img-teaser" src="http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg" alt="Card 1 image">
      </div>
      <div class="card__content-box">
        <div class="text-box">
          <h3>Choosing your elderly care at home</h3>
          <date>04 Nov, 2016</date>
        </div>
      </div>
  </div>

  <div class="card">
      <div class="card__image-box">
        <img class="img-teaser" src="http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg" alt="Card 1 image">
      </div>
      <div class="card__content-box">
        <div class="text-box">
          <h3>Choosing your elderly care at home</h3>
          <date>04 Nov, 2016</date>
        </div>
      </div>
  </div>

  <div class="card">
      <div class="card__image-box">
        <img class="img-teaser" src="http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg" alt="Card 1 image">
      </div>
      <div class="card__content-box">
        <div class="text-box">
          <h3>Choosing your elderly care at home</h3>
          <date>04 Nov, 2016</date>
        </div>
      </div>
  </div>

</div>

Upvotes: 0

Views: 105

Answers (1)

wlh
wlh

Reputation: 3525

In the CSS, give your each of your card classes a percentage that adds up to 100; since children inherit the width of parent elements, the percentages of all div's with class="card" will be added together.

width + padding + border + margin = total size

And so, in your case:

.cards-list{
            width: 90%;
            max-width: 980px;


        .card{
            float: left; /* or right */
            width: 32%;
            margin-right: 1.333333%;

Since you have only 3 elements with the card class, this will fill up the entire card-list div element. 32% width + 1.33% margin-right = 33.33% / card.

When you add elements, recalculate the percentages.

Here is your code working with four "card"'s: https://jsfiddle.net/crvu1oc9/1/

Upvotes: 1

Related Questions