Rob J Rob J - 4 months ago 12
CSS Question

Extra Space Between inline-block DIV Elements

I am creating a fluid layout using the CSS column layout module and am seeing unexpected results when 2 or more elements are in the same 'row' of a column. A 3 to 4 px gap will appear between the elements. I've tested in IE11, FireFox 24, Chrome 31, and Safari 5.1.7 and they all exhibit the same behavior.

<div class="tile-container">
<div class="tile-large">1</div>
<div class="tile-wide">2</div>
<div class="tile-small">3</div>
<div class="tile-small">4</div>
<div class="tile-small">5</div>
<div class="tile-small">6</div>
<div class="tile-wide">7</div>
<div class="tile-large">8</div>
</div>

.tile-container {
-moz-column-width: 250px;
-webkit-column-width: 250px;
column-width: 250px;
column-fill: auto;
height: 502px;
background-color: gray;
}

.tile-large {
width: 250px;
height: 250px;
-webkit-column-break-inside: avoid;
break-inside: avoid;
display: inline-block;
background-color: green;
}

.tile-wide {
width: 250px;
height: 125px;
-webkit-column-break-inside: avoid;
break-inside: avoid;
display: inline-block;
background-color: blue;
}

.tile-small {
width: 125px;
height: 125px;
-webkit-column-break-inside: avoid;
break-inside: avoid;
display: inline-block;
background-color: red;
}


I don't want to start using negative margins to close the gap as I want to introduce drag/drop behavior. Float left will remove the gap, but that introduces another set of issues. Oddly enough, when I use jQueryUI sortable, after the drop event and jQueryUI arranges the elements, the gap is no longer there.

Answer

You need to comment out the white space between the elements, like so:

<div class="tile-container">
       <div class="tile-large">1</div><!--
    --><div class="tile-wide">2</div><!--
    --><div class="tile-small">3</div><!--
    --><div class="tile-small">4</div><!--
    --><div class="tile-small">5</div><!--
    --><div class="tile-small">6</div><!--
    --><div class="tile-wide">7</div><!--
    --><div class="tile-large">8</div>
</div>

DEMO: http://jsfiddle.net/P7cbA/11/

Another way is to put the elements in the HTML in one line without any spaces between them, but this reduces the code readability:

<div class="tile-container">
       <div class="tile-large">1</div><div class="tile-wide">2</div><div class="tile-small">3</div><div class="tile-small">4</div><div class="tile-small">5</div><div class="tile-small">6</div><div class="tile-wide">7</div><div class="tile-large">8</div>
</div>