如何制作一个改变整个屏幕背景的div

我尝试了这个,但它仅在屏幕位于垂直滚动条出现之前才有效,然后当您向下滚动时背景颜色又回到白色。


.background {

  min-height: 100vh;

  width: 100vw;

  position: absolute;

  top: 0;

  z-index: -9999;

  background-color: red;

}

<div class="background"></div>


慕少森
浏览 87回答 1
1回答

有只小跳蛙

问题是默认情况下body有填充。“Manjuboyz”解决方案在一定程度上有效,但全球应用的风格可能会在未来引起问题。此代码片段将通过删除默认的正文填充来修复此问题:<!DOCTYPE html><html><head>&nbsp; &nbsp; <title></title>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; body{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; padding:0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; margin: 0;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; .background {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; min-height: 100vh;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width: 100vw;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; position: absolute;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; top: 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; z-index: -9999;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; background-color: red;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style>&nbsp; &nbsp; <script>&nbsp; &nbsp; </script></head><body>&nbsp; &nbsp; <div class="background"></div></body></html>展开片段但是,如果您的页面太长,您将需要该position: fixed属性,这可以确保 div 通过将其“固定”到可见的可查看屏幕来遵循其设备上的渲染视图区域。W3有一些很好的例子。<!DOCTYPE html><html><head>&nbsp; &nbsp; <title></title>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; body{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; padding:0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; margin: 0;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; .background {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; min-height: 100vh;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width: 100vw;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; position: fixed;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; top: 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; z-index: -9999;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; background-color: red;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style>&nbsp; &nbsp; <script>&nbsp; &nbsp; </script></head><body>&nbsp; &nbsp; <div class="background"></div></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5