我试过这个CSS代码:
background: url(bg.jpg) center center no-repeat fixed;
background-size: cover;
但背景图像的高度仍然大于视口(viewport)。为什么会这样?请不要只给我代码,还要解释一下。
最佳答案
来自 MDN :
cover A keyword that is the inverse of contain. Scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). The image "covers" the entire width or height of the container. When the image and container have different dimensions, the image is clipped either left/right or top/bottom.
它比视口(viewport)高,因为这是在不改变纵横比的情况下使其足够宽以填充视口(viewport)的唯一方法。
使用 100% 100%
缩放它同时打破纵横比。
如果文档内容使正文高于视口(viewport),您可能还必须设置 background-attachment: fixed
以强制它缩放到窗口而不是正文元素。
关于html - 如何使背景图像适合屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884387/