1

I have an HTML template with a series of blocks, which are just "inline-block". Initially, a number of blocks are rendered as part of the template, but users may add additional blocks, which then get appended dynamically.

My problem is that the dynamically added blocks have a different spacing compared to the pre-rendered ones.

Check out this fiddle: https://jsfiddle.net/7w3hu5gk/

It is clear that the blocks, added dynamically by the Javascript code, don't line up vertically.

HTML:

<div id="blocks">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

CSS:

#blocks {
  width:140px;
}
#blocks div.block {
  display:inline-block;
  *display:inline; // Legacy IE love
  zoom:1;
  vertical-align:top;
  width:20px;
  height:20px;
  margin:5px;
  border:1px solid red;
  background:1px solid #777;
}

It seems that the culprit is the inherent (and invisible) character spacing, since inline-block makes elements behave sort-of-like text. Setting font-size: 0 on the #blocks element will magically fix the problem. But then the font size of text contained within the div.blocks elements have to be resized.

Does anyone have a nice fix for this?

  • Floating elements (e.g. float: left;) are not a desirable alternative.
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Kafoso
  • 534
  • 3
  • 20

3 Answers3

3

This is due to there being a new line between each div in your HTML. This makes the browser think it needs to add a space in between each element.

Either remove the spacing or add font-size:0; to your parent div.

Fiddle for option 1: https://jsfiddle.net/Lu0xw1b6/

Fiddle for option 2: https://jsfiddle.net/fkcb5mrw/

Wowsk
  • 3,637
  • 2
  • 18
  • 29
  • Ah. Of course. So, in fact, it was the static (i.e. not dynamically added) elements which had wrong spacing. Nifty. Thanks for the answer. :) – Kafoso Aug 18 '16 at 13:32
2

Use a flexbox on the blocks div and there you go!

#blocks {
    display: flex;
    flex-wrap: wrap;
}

see fiddle here.

kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • Seems IE goes apeshit over this, though: http://caniuse.com/#search=flex-wrap No surprisingly. I guess `font-size: 0` really is the way to go for global coverage. – Kafoso Aug 18 '16 at 13:35
0

Hi try this code.

#blocks {
  width:140px;
  letter-spacing: -0.31em;
  *letter-spacing: normal;
  *word-spacing: -0.43em;
}
#blocks .block {
    display: inline-block;
    *display: inline;
    zoom: 1;
    letter-spacing: normal;
    word-spacing: normal;
    vertical-align: top;
    width:20px;
    height:20px;
    margin: 0 5px 5px;
    border:1px solid red;
    background:1px solid #777;
}

Regards :)

jseezo
  • 462
  • 3
  • 4
  • Fiddling around with letter spacing is, in my eyes, a little nastier than just setting font-size to zero. But thanks :) – Kafoso Aug 18 '16 at 13:28