【问题标题】:CSS border width changing layout [duplicate]CSS边框宽度更改布局[重复]
【发布时间】:2020-01-30 08:38:33
【问题描述】:
当我将边框宽度从 1px 更改为 0px 时遇到问题。
这会改变 div 的布局。 div应该在margin的影响下逐步堆叠,但是当我设置border width为0px时,top margin变成了0px。
这是我的代码。
div {
height: 300px;
width: 50%;
margin: 10px;
border: 1px solid red;
}
.red {
background-color: #ffcccc;
}
.green {
background-color: #ccffcc;
}
.blue {
background-color: #ccccff;
}
.purple {
background-color: #cccccc
}
<div class="red">
<div class="green">
<div class="blue">
<div class="purple"></div>
</div>
</div>
</div>
【问题讨论】:
标签:
html
css
width
border
margin
【解决方案1】:
在标准 html 内容框模型中,宽度仅为框内容的宽度。如果您为其添加填充和/或边框,这些将添加到框宽度(在您的情况下为 50% + 1px + 1px)。
您可以通过选择使用不同的框模型来更改此行为,即边框框模型:在这种情况下,您指定的宽度将始终包括填充和边框。
你可以这样做:
<style>
div {
box-sizing: border-box;
height: 300px;
width: 50%;
margin: 10px;
border: 1px solid red;
}
.red { background-color: #ffcccc; }
.green { background-color: #ccffcc; }
.blue { background-color: #ccccff; }
.purple { background-color: #cccccc}
</style>
有关详细信息,请参阅 here 和 here。
【解决方案2】:
你可以试试这个
div {
height: 300px;
width: 50%;
padding: 1px;
margin:10px;
border:0px solid red;
}
.red {
background-color: #ffcccc;
}
.green {
background-color: #ccffcc;
}
.blue {
background-color: #ccccff;
}
.purple {
background-color: #cccccc;
}
<div class="red">
<div class="green">
<div class="blue">
<div class="purple"></div>
</div>
</div>
</div>
【解决方案3】:
您可以使用此代码
body {
margin: 0;
padding: 0;
}
div {
height: 300px;
width: 50%;
margin: 10px;
border: 0px solid red;
float: left;
}
.red {
background-color: #ffcccc;
}
.green {
background-color: #ccffcc;
}
.blue {
background-color: #ccccff;
}
.purple {
background-color: #cccccc;
}
<div class="red">
<div class="green">
<div class="blue">
<div class="purple"></div>
</div>
</div>
</div>
【解决方案4】:
应该这样做!
<style>
div {
height: 300px;
width: 50%;
margin: 10px;
box-shadow:inset 0px 0px 0px 1px red;
}
.red { background-color: #ffcccc; }
.green { background-color: #ccffcc; }
.blue { background-color: #ccccff; }
.purple { background-color: #cccccc}
</style>
<div class="red">
<div class="green">
<div class="blue">
<div class="purple"></div>
</div>
</div>
</div>