使用“背景尺寸:封面”的 CSS 背景不适合全高
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17734428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS background using "background-size: cover" doesn't fit the full height
提问by apocryphalauthor
I'm making a page that will just display an SVG image, and here are the requirements:
我正在制作一个只显示 SVG 图像的页面,以下是要求:
- the vector should take up the entire window
- the vector should maintain its aspect ratio (defined in the SVG file itself)
- the vector should crop/clip in order to prevent skewing
- 向量应该占据整个窗口
- 矢量应保持其纵横比(在 SVG 文件本身中定义)
- 矢量应该裁剪/剪辑以防止倾斜
The CSS...
CSS...
body {
background: url(/path/to/image.svg);
background-size: cover;
}
...works almostperfectly except that when the browser window becomes too narrow it tiles instead of cropping/clipping.
...工作几乎完美,除了当浏览器窗口变得太窄时,它会平铺而不是裁剪/剪裁。
Here are some screen shots (please ignore the artifacts left by dabblet):
下面是一些屏幕截图(请忽略 dabblet 留下的工件):
Here the window is close to the aspect ratio of the original image
这里的窗口接近原始图像的纵横比
Here the window is "shorter" than the aspect ratio, and the image is cropping (as desired).
这里窗口比纵横比“短”,并且图像正在裁剪(根据需要)。
Here the window is "narrower" than the aspect ratio, but instead of cropping, the image is tiling (undesired).
这里的窗口比纵横比“窄”,但不是裁剪,图像是平铺的(不需要)。
Here are some thoughts that I had...
以下是我的一些想法...
- Could I change the SVG image in some way to prevent this from happening?
- Could I markup/style the page to achieve the desired results?
- I would prefer to keep in the realm of HTML/CSS, but if Javascript is needed, then so-be-it.
- 我可以以某种方式更改 SVG 图像以防止这种情况发生吗?
- 我可以标记/设置页面样式以达到预期的结果吗?
- 我更愿意留在 HTML/CSS 领域,但如果需要 Javascript,那么就这样吧。
Here's the dabblet that I was working with... http://dabblet.com/gist/6033198
这是我正在使用的小玩意儿... http://dabblet.com/gist/6033198
回答by apocryphalauthor
After some trial-and-error, this is what I found.
经过一些反复试验,这就是我发现的。
Adding (to the original CSS):
添加(到原始 CSS):
html {
height: 100%
}
delivered exactly what I was looking for in the original spec.
准确地交付了我在原始规范中寻找的内容。
Additionally, if I wanted the image to be center when it was cropped, I could use:
此外,如果我希望图像在裁剪时居中,我可以使用:
html {
background: url(path/to/image.jpg) no-repeat center center fixed;
background-size: cover;
}
Lastly, if I wanted it to be centered, always maintain the aspect ratio, but NOT be cropped (i.e., some whitespace is OK) then I could do:
最后,如果我希望它居中,始终保持纵横比,但不要被裁剪(即,一些空白是可以的),那么我可以这样做:
body {
background: url(/path/to/image.svg) no-repeat center center fixed;
background-size: contain;
}
回答by Raghibsuleman
This css is working.Thanks
这个 css 正在工作。谢谢
"background-size: contain;"
.cover{background:url(images/cover.jpg) no-repeat top center; display:inline-block; width:100%; height:400px; background-size: contain;}
<div class="cover"> </div>