【问题标题】:CSS background-size propertyCSS 背景尺寸属性
【发布时间】:2014-10-30 16:34:51
【问题描述】:

我想为我的网站添加全尺寸背景,最好只使用 CSS 属性 backgroundbackground-size。目前我正在使用以下

.bg {
  background: url("./gfxGeneral/backgroundImage.jpg");
  background-size: cover;
  background-repeat: no-repeat;
}

然后<body class="bg"> 应用它。问题是,如果窗口变得非常窄,我使用的横向背景图像只会覆盖一小部分,因为它会将自身缩放到 100% 的宽度。无论如何我可以让它使用 either 100% 宽度或 100% 高度,并且不会留下任何白色背景?我为此找到了一些指南,但它们都涉及相当“丑陋”的代码。

奖励请求:最好使用支持旧浏览器(如 IE9)的代码

【问题讨论】:

  • 为什么不直接向谷歌询问“css 背景大小”?
  • 我做到了,但我发现的“简单”解决方案都没有为我工作。在讨论过于复杂的解决方案之前,我想问问你们。
  • 另外,选项 'background-size: 100% 100%;' 使背景图像全宽,但高度仅为 10-15 像素。

标签: html css background background-size


【解决方案1】:

仅当您的 body 元素与窗口一样大时,其他答案的建议才有效。

如果body 的大小不是完整的窗口大小,您可以尝试使用 JavaScript(我使用的是 jQuery 框架):

<script>
$(document).ready(function() {
    // Call the function at the beginning, in case the window is already too small, 
    onResize();

    $(window).resize(function() {
        onResize();
    });

    function onResize() {
        // Note: 16 / 9 is the resolution of the background image
        // Change appropriately
        if ($(window).width() / $(window).height() < 16 / 9) {
            $(".bg").css("background-size", "auto " + $(window).height() + "px");
        }
        else {
            $(".bg").css("background-size", "cover");
        }
    }
});
</script>

this JFiddle

希望这会有所帮助!

【讨论】:

  • 这确实有效,不过我确实有两个简短的问题: 1. 为什么 body 元素至少与窗口的高度不同? 2. 有没有办法让它在背景中居中,至少水平居中?
  • @Noceo 我会尝试回答你的问题:1)body 元素只是所有其他 html 元素的容器,并根据包含的元素调整自己的高度。如果里面没有元素,它的高度将为0。
  • 谢谢。有没有办法让它全高?尝试在 CSS 中为 body 元素添加“min-height: 100%”。
  • @Noceo 2) 有 css 属性 background-position 可以对齐图像。 w3schools 有一些关于它的信息。尝试使用background-position: center top;
  • @Noceo 使其全高度使用html, body { min-height: 100%; }。做了一些研究,我实际上找到了一种不用 Javascript 的方法:jsfiddle.net/so2f5fq3
【解决方案2】:

使用 css 试试这个:

.bg {
  background: url("./gfxGeneral/backgroundImage.jpg");
  background-size: 100% 100%;             //x% y%, first is width and second is height
  background-repeat: no-repeat;
}

希望这行得通。

【讨论】:

  • 这就像我不小心以一种无法找到浏览器窗口的完整高度的方式进行布局。这会导致此方法在背景高度和元素位置(如
    ) 方面产生一些非常奇怪的问题
【解决方案3】:

您可以使用 CSS 的“min-height”和“vh”单元来强制 body 元素至少与视口一样高,而不是使用 javascript:

http://jsfiddle.net/s9ggm2u1/5/

body.bg {
    background[...]

    min-height: 100vh;
    margin:0px;
}

浏览器对 vh 单位的支持: http://caniuse.com/#search=vh

【讨论】:

    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 2012-12-13
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2019-04-28
    相关资源
    最近更新 更多