css - 尽管使用了盒子大小,边距仍被添加到总宽度中
问题描述
我遇到了一个问题,即我的元素的边距被添加到它们的总宽度中,而不是在计算宽度之前被考虑在内,尽管使用了该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>
我希望输出在左侧有侧边栏,在它旁边有内容,但能够在不扭曲模型的情况下定义边距/填充。
解决方案
您需要添加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
andmargin-right
转到padding-left
andpadding-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>
推荐阅读
- apache-nifi - Nifi - 在前一个流文件完全通过下游后激活流文件
- javascript - 反应路由器dom:路由和路由器根本不起作用
- excel - 计数与另一个单元格中的值匹配的单元格
- node.js - 如何使用 webpack 将多个节点 js 文件组合成一个包
- c++ - std::promise 和 std::future 的生命周期
- powershell - Powershell 脚本给出错误 Get-ChildItem: 找不到路径
- javascript - Discord 机器人不阅读 message.content
- django - Django 会话表单(临时保存表单)
- javascript - 尝试使用 removeChild 覆盖和删除元素时出错
- c# - ASP.NET Core - 创建基本控制器端点 - 当子控制器端点也存在时