Html 如何通过 CSS 使背景图像/图像拉伸以填充容器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12601913/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:03:08  来源:igfitidea点击:

How to get background image/ image to stretch to fill container via CSS?

htmlcsssvgbackground-image

提问by user137263

I have a scale vector image and I want it to fill a container. There's a couple of these sort of questions on SO, although they are a tad old. E.g. Stretch and scale CSS background

我有一个比例矢量图像,我希望它填充一个容器。关于 SO 有几个这样的问题,尽管它们有点老了。例如拉伸和缩放 CSS 背景

However, when I've attempted to implement such solutions the results have been disappointing.

但是,当我尝试实施此类解决方案时,结果令人失望。

For instance:

例如:

    body  {

    margin: 0; 
    padding: 0;
    text-align: center; 
    color: #000;
    background-color: #000
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 100%;

}

...

.twoColLiqLtHdr #container {
    width: 80%;
    margin: 0 auto; 
    border: 2px solid #000000;
    text-align: left; 
    background-color: #003;
    background-image: url('background_image.svg'); 
    /*background-position: 80% 80%; */

  background-repeat: no-repeat; 
    color: #000;
    font-family: "Times", cursive;


    background-attachment:fixed;
    min-height:100%;
    /*top: 0;
    left: 0; */



} 

I've tried various arrangements but I cannot make it stretch without leaving blank areas (repeating is a success of sorts, but looks horrible).

我尝试了各种安排,但我无法在不留下空白区域的情况下进行拉伸(重复是一种成功,但看起来很糟糕)。

However, since I'm working with a svg am I approaching this in perhaps the wrong way, should I be using a svg xmlns tag in the html instead? (P.S. I'm aware of IE8's absolute inability to handle svgs)

但是,由于我正在使用 svg,我是否以错误的方式处理这个问题,我应该在 html 中使用 svg xmlns 标签吗?(PS 我知道 IE8 绝对无法处理 svgs)

回答by Giona

Have you tried

你有没有尝试过

background-size:cover;

Check some examples.

检查一些例子

I had issues with webkit, background-size:coverand SVG background images. I solved it adding

我遇到了 webkitbackground-size:cover和 SVG 背景图像的问题。我解决了它添加

-webkit-background-origin:border;

回答by Robert Longson

you probably need to add preserveAspectRatio="none" as an attribute of the outer <svg>element in the SVG image itself.

您可能需要<svg>在 SVG 图像本身中添加 preserveAspectRatio="none" 作为外部元素的属性。

If you don't want to modify the image file then you could try

如果您不想修改图像文件,则可以尝试

background-image: url('background_image.svg#svgView(preserveAspectRatio(none))');

背景图片:url('background_image.svg#svgView(preserveAspectRatio(none))');

Firefox 15 would support that and probably other UAs too.

Firefox 15 将支持这一点,也可能支持其他 UA。