html - 如何使背景图像适合屏幕?

标签 html css

我试过这个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/

相关文章:

javascript - 将 JavaScript 中的值集成到 HTML 表单中以将其发布到 php 中

android - 用户更改方向后,网站无法正确显示全屏背景

html - Safari Mobile Multi-Line <Select> aka GWT Multi-Line ListBox

html - 如何设置:disabled pseudo element/class on :before pseudo element

css - 将边框颜色添加到范围旋钮 ionic-range

html - DIV 更改页面缩放位置

javascript - DIV 中的长 UL 列表,自动滚动到 LI 元素

css - 鼠标悬停事件要求所需的解决方案

javascript - jQuery 不更改动态创建图像的图像源属性

html - 无法加载字体