Div 不填充父级宽度:100%

luc*_*rot 5 html css

html

<main>
    <div class="homediv">
        <p>test</p>
    </div>
</main
Run Code Online (Sandbox Code Playgroud)

CSS

div.homediv {
  background-color: yellow;
  width: 100%;
  position: static;
  /*The lower the z-index, the further in the background the element*/
  z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)

乍一看,这应该使 div 水平填满屏幕。但事实并非如此。这里的一些答案说 width:100% 仅当设置了父级的宽度时才起作用,但那已经设置了。为了确保这一点,我什至给 html、body、main 和我的 div 设置了 width:100% 属性。这并没有解决它。

luc*_*rot 1

在 chrome DevTools 中进行一些尝试后,我发现 main 确实填充了屏幕宽度。但它包含一些看似预设的属性,我必须将其删除。谷歌告诉我,填充和边距 - 如果没有指定 - 由浏览器设置,因此要修复CSS,我必须添加

main {
  padding:0;
  margin:0;
}
Run Code Online (Sandbox Code Playgroud)