Search code examples
htmlcssmargin

CSS quirk of horizontal margin


I'm using codepen to play some CSS practice and encounter an error.

<style>
    * {
      box-sizing: border-box;
      margin: 0;
    }

    .container {
      width: 300px;
      background-color: pink;
      margin: 0 auto;
    }

    .one, .two {
      width: 100px;
      height: 100px;
      margin: 10px;
      background-color: black;
      border: none;
      display: inline-block;
    }
</style>

<div class='container'>
  <span>
    <div class='one'></div>
    <div class='two'></div>
  </span>
</div>

The width of the span should be 10 + 100 + 10 + 10 + 100 + 10 = 240px . But chrome tool says it's 244.44px


Solution

  • That's due to the whitespace created by the linebreaks in the HTML code. If you write it all in one line, it becomes 240px wide:

    * {
      box-sizing: border-box;
      margin: 0;
    }
    
    .container {
      width: 300px;
      background-color: pink;
      margin: 0 auto;
    }
    
    .one,
    .two {
      width: 100px;
      height: 100px;
      margin: 10px;
      background-color: black;
      border: none;
      display: inline-block;
    }
    <div class='container'>
      <span><div class='one'>1</div><div class='two'>2</div></span>
    </div>

    If you don't want that, you can either move all closing tags (for example </div>) to the next line, or use (empty) HTML comments at the end and beginning of lines:

    * {
      box-sizing: border-box;
      margin: 0;
    }
    
    .container {
      width: 300px;
      background-color: pink;
      margin: 0 auto;
    }
    
    .one,
    .two {
      width: 100px;
      height: 100px;
      margin: 10px;
      background-color: black;
      border: none;
      display: inline-block;
    }
    <div class='container'>
      <span><!--
      --><div class='one'>1
      </div><div class='two'>2
      </div><!--
      --></span>
    </div>