CSS水平边缘的怪癖

时间:2017-04-24 17:08:49

标签: html css margin

我正在使用codepen来玩一些CSS练习并遇到错误。

<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>

跨度的宽度应为10 + 100 + 10 + 10 + 100 + 10 = 240px。 但是chrome工具说它是244.44px

1 个答案:

答案 0 :(得分:0)

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>

相关问题