尽管使用了框大小,但边距仍添加到总宽度中

时间:2020-01-27 19:13:10

标签: css width margin display box-sizing

我遇到了一个问题,尽管使用box-sizing: border-box属性,但元素的边距却被添加到元素的总宽度中,而不是在计算宽度之前将其考虑在内。

因此,基本上,我有2个元素:边栏和主要内容div,它们在没有边距的情况下整齐地堆叠在一起。但是,一旦我添加了边距,边栏就会爬到内容的顶部。

* {
  font-family: 'Roboto', sans-serif;
}

body {
  width: 1265px;
  display: inline-block;
  box-sizing: border-box;
}

main {
  margin: auto;
}

.centerContent {
  width: 75%;
  margin: auto;
  float: right;
}

.sidebar {
  width: 25%;
  height: 100%;
  margin-top: 10px;
  float: left;
  background-color: #eaf4f7;
  margin-left: 10px;
  margin-right: 10px;
}

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

code {
  width: 600px;
  font-family: 'Source Code Pro', monospace;
  color: #43892a;
  background-color: #000;
  display: block;
}

header {
  margin-left: 15px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #a72525;
}
<body>
  <header>
    <h1>Batch Documentation</h1>
  </header>
  <main class="clearfix">
    <div class="sidebar">
      <ul>
        <li>Test</li>
        <li>Test2</li>
        <li>Test3</li>
      </ul>
    </div>
    <div class="centerContent">
      <h2>Sample text</h2>
      <code>Hello</code>
    </div>
  </main>
</body>

我希望输出的左侧有侧边栏,其旁边是内容,但是能够定义边距/填充而不会扭曲模型。

1 个答案:

答案 0 :(得分:0)

您需要在通用选择器中添加box-sizing:border-box;,并检查以下内容:https://www.w3schools.com/cssref/css3_pr_box-sizing.asp

* {
  box-sizing:border-box;
  font-family: 'Roboto', sans-serif;

}

此后,您需要在侧边栏类中进行一些更改,将margin-leftmargin-right更改为padding-leftpadding-right

.sidebar {
    width: 25%;
    height: 100%;
    margin-top: 10px;
    float: left;
    background-color: #eaf4f7;
    padding-left: 10px;
    padding-right: 10px;
}

随着填充设置width: 25%;中的空间,边距设置width: 25%;周围的空间,因此这会使25%的值变大,并且布局分成两行

更新

使用边距代替填充,您可以添加width: calc(25% - 20px);,第一个值是div的宽度,第二个值是边距值的总和

* {
  font-family: 'Roboto', sans-serif;
}

body {
  width: 1265px;
  display: inline-block;
  box-sizing: border-box;
}

main {
  margin: auto;
}

.centerContent {
  width: 75%;
  margin: auto;
  float: right;
}

.sidebar {
   width: calc(25% - 20px);
    height: 100%;
    margin-top: 10px;
    float: left;
    background-color: #eaf4f7;
    margin-left: 10px;
    margin-right: 10px;
}

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

code {
  width: 600px;
  font-family: 'Source Code Pro', monospace;
  color: #43892a;
  background-color: #000;
  display: block;
}

header {
  margin-left: 15px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #a72525;
}
<body>
  <header>
    <h1>Batch Documentation</h1>
  </header>
  <main class="clearfix">
    <div class="sidebar">
      <ul>
        <li>Test</li>
        <li>Test2</li>
        <li>Test3</li>
      </ul>
    </div>
    <div class="centerContent">
      <h2>Sample text</h2>
      <code>Hello</code>
    </div>
  </main>
</body>