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

问题描述 投票:0回答:1

我遇到了一个问题,尽管使用了

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>

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

css width margin display box-sizing
1个回答
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-left
margin-right
更改为
padding-left
padding-right

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

正如 padding 设置

 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>

© www.soinside.com 2019 - 2024. All rights reserved.