Search code examples
csswhitespaceword-wrapremoving-whitespace

remove space between divs


Question: Why is there a space between the two div tags?

Here is the JSFiddle

Screenshot:

enter image description here

//HTML

<div class='row'>
    <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
    </div>
    <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
    </div>
</div>

//CSS

.row{
    background-color: red; 

    margin: 2em 0;
    display: block;
    text-align: center;
    white-space: nowrap;
    -webkit-box-shadow: 0 1px 5px rgba(0,0,0,.6) inset;
    box-shadow: 0 1px 5px rgba(0,0,0,.6) inset;  
}
.item{
    background-color: silver;

    width: 50%;
    white-space: normal;
    display: inline-block;
}
.sub-item{
    background-color: royalblue;

    margin: .5em;
    width: 100px;
    height: 100px;
    text-align: center;
    display: inline-block;
}

Solution

  • Why is there a space between the two div tags?

    You can read more about it in Fighting the Space Between Inline Block Elements

    To remove the undesired blank space, set font-size: 0 in the .row element, and then restore the font-size in the .item.

    .row {
        font-size: 0;
    }
    
    .item {
        font-size: 12px;
    }
    

    Since your margins are using the the em unit, if you simple set the font-size: 0 in the wrapper element, your margins will disappear aswell.

    To keep your margins, it's important to restore the font-size in the inner element or set the margins using another unit that is not based on the font-size, like px.

    Following is an example:

    .row {
      background-color: red;
      margin: 2em 0;
      display: block;
      text-align: center;
      white-space: nowrap;
      -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .6) inset;
      box-shadow: 0 1px 5px rgba(0, 0, 0, .6) inset;
      font-size: 0;
    }
    .item {
      font-size: 12px;
      background-color: silver;
      width: 50%;
      white-space: normal;
      display: inline-block;
    }
    .sub-item {
      background-color: royalblue;
      margin: .5em;
      width: 100px;
      height: 100px;
      text-align: center;
      display: inline-block;
    }
    <div class='row'>
      <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
      </div>
      <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
      </div>
    </div>