如何设置div背景图全屏显示 遮挡body的蓝色背景
问题描述
给div设置背景图后无法覆盖全屏,div周围存在空隙,露出的蓝色为body元素的背景色。
问题参考截图
当前编写的代码如下:
#one{ background:linear-gradient(0deg, rgba(0, 0, 0, 0.7) 10% , rgba(0, 0, 0, 0) 60%, rgba(0, 0, 0, 0.7) 75%), url("https://picsum.photos/500"); padding-top: 168px; padding-bottom: 100px; color: white; border: none; background-size: cover; }
<div id="one"> <center> <p id="p1">Unlimited movies, TV <br>shows and more.</p> <p id="p2">Watch anywhere. Cancel anytime.</p> <p id="p3">Ready to watch? Enter your email to create or restart your membership.</p> <input id="mail" type="text" > <input id="mailb" type="submit" value="Get Started"> </center> </div>
问题原因
空隙来自浏览器默认样式:所有主流浏览器都会给<body>标签默认添加8px的外边距,没有重置这个默认样式时就会露出body的蓝色背景。你给#one设置的background-size: cover本身写法正确,问题不在背景属性上。
修复方法
- 在CSS最顶部添加全局重置样式,清除浏览器默认的内外边距,避免默认样式干扰布局:
* { margin: 0; padding: 0; box-sizing: border-box; }
- 如果需要这个div不仅宽度铺满,高度也能占满整个屏幕,可以补充以下样式:
html, body { width: 100%; min-height: 100%; } #one { /* 保留原有所有属性,新增下面三个属性即可 */ width: 100%; min-height: 100vh; background-position: center; }
补充说明:
100vh指当前浏览器视口的高度,background-position: center可以让背景图始终居中显示,不会因为窗口尺寸变化出现显示偏移。
- 额外提示:
<center>是HTML已经废弃的标签,不推荐继续使用,后续实现内容居中可以给父元素加text-align: center属性,或者用flex、grid布局实现,兼容性和可维护性更好。
内容的提问来源于stack exchange,提问作者Lakshya Kashyap
相关产品推荐
相关产品推荐

