首页 > 解决方案 > 尽管使用了盒子大小,边距仍被添加到总宽度中

问题描述

我遇到了一个问题,即我的元素的边距被添加到它们的总宽度中,而不是在计算宽度之前被考虑在内,尽管使用了该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>

我希望输出在左侧有侧边栏,在它旁边有内容,但能够在不扭曲模型的情况下定义边距/填充。

标签: csswidthmargindisplaybox-sizing

解决方案


您需要添加box-sizing:border-box;通用选择器,请查看:https ://www.w3schools.com/cssref/css3_pr_box-sizing.asp

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

}

之后,您需要在侧边栏类中进行一些更改,将您的margin-leftandmargin-right转到padding-leftandpadding-right

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

由于 padding 设置了 内的空间width: 25%;,margin 设置了 周围的空间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>


推荐阅读