<分区>
<分区>
我正在创建一个叠加层,但右侧的宽度最终是错误的。我哪里出错了?最后,我想要一些占屏幕 100% 宽度的按钮,减去一些边距。
body
{
width: 100%;
margin: 0px;
}
.a1
{
background-color: rgba(0, 0, 0, 0.7);
position: fixed;
width: 100%;
height: 100%;
z-index: 1;
}
.a2 {
width: 100%;
border: 5px solid blue;
}
<div class="a1">
<div class="a2">The width is going to far on the right</div>
</div>
最佳答案
您不需要在子 div a2
上指定 width: 100%
。作为 block 元素,它会自动填充父元素的可用宽度,该宽度设置为 100%
。
您的 a2
CSS 变为:
.a2 {
border: 5px solid blue;
}
通过这种方式,您的边距将得到尊重并按预期工作:
* {
box-sizing: border-box;
}
body
{
width: 100%;
margin: 0px;
}
.a1
{
background-color: rgba(0, 0, 0, 0.7);
position: fixed;
width: 100%;
height: 100%;
z-index: 1;
}
.a2 {
border: 5px solid blue;
}
<div class="a1">
<div class="a2">The width is going to far on the right</div>
</div>
在关于元素大小的 OP 评论之后
我注意到您没有特别提到您正在使用 border-box
作为您的 box-sizing
方法。我现在已将其添加到代码段中。
使用 border-box
意味着当您指定框的大小时,您将在该大小内包含边框。
例如,如果宽度设置为 100%,这就是 100%包括元素上的任何边框。大多数规范化样式表默认将 box-sizing
设置为 border-box
。
关于css - 如何使用 CSS 在叠加层中获得 100% 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376559/