如何在CSS [duplicate]中正确获得100%的宽度

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

我正在创建叠加层,但宽度最终在右侧错误。我哪里出错了?最后,我想要一些屏幕宽度为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>
css width overlay margin
1个回答
0
投票

您无需在子div width: 100%上指定a2。作为块元素,它将自动填充父元素的可用宽度,该宽度设置为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

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