0

I have a simple set of cards that show side-by-side images, which I need to be responsive to screen width. So using simple inline-block, I have this structure:

<div class="cards" id="ex1">
  <div class="card">
    <img src="http://www.clker.com/cliparts/5/b/a/7/1194986784455829849basebalm_ganson.svg.med.png" />
  </div>
  <div class="card">
    <img src="http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png" />
  </div>
</div>

With this CSS:

.cards {
  display: inline-block;
  border: 2px solid #808080;
  border-radius: 2px;
  padding: 10px;
  margin-bottom: 20px;
}

#ex1 .card {
  width: 35%;
  display: inline-block;
}

But to my surprise, the parent div, .cards, spans the width of the page as if it were display: block:

enter image description here

However, if I hard-code the widths of the .card divs, it works as expected. Here's a fiddle that compares the two.

Why does inline-block not respect percentages that don't add up to 100%? Is there any way to do this with percentages? (I could make them both 50%, but even with box-sizing: border-box this can cause them to stack vertically.)

Chris Wilson
  • 6,599
  • 8
  • 35
  • 71

2 Answers2

4

.cards has a shrink-to-fit width. That means it will attempt to be only as wide as the contents want (supposing there is enough space).

However, the contents have a percentage width, which depends on .cards.

The circular definition is solved like this:

  1. The percentages of the contents are treated as auto

    That is, the images have their intrinsic width, which is 300px.

  2. .cards is sized according to the contents, which no longer depend on .cards

    That is, it becomes 300px + 300px = 600px wide. Well, in fact slightly more because you have some space in the HTML, see How to remove the space between inline-block elements? to avoid it, but let's ignore this.

  3. The contents are sized again, now taking the percentages into account, which are resolved relatively to the width of .cards from the previous step.

    That is, the images become 35% * 600px = 210px wide.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
2

The inline-block property occupies 100% space while maintaining the property of being inline. However, when a single line on the visual appearance is about to overflow, the inline-property goes on another line.

For example:

element {
    display: inline; /* Makes the content go on the same line*/
}
element {
    display: inline-block; /* Makes the content go on the same line while not overflowing
                           and going on a different line while about to overflow*/
}
element {
    display: block; /* Makes the content go on different lines*/
}

I hope you understand what I mean.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Yash Jain
  • 1
  • 5
  • 20