如何设置背景大小的最小宽度

时间:2013-05-21 20:47:43

标签: css html5 css3

我的图像是1000px X 600px。我想将它用作div的响应背景,但是尽管浏览器窗口有多小,但我想设置最小宽度为1000px。

这很令人沮丧,因为似乎没有一种简单的方法来定义min。宽度。

如果我使用background-size:cover - 由于某种原因,图像默认大于1000px。

请帮助

4 个答案:

答案 0 :(得分:18)

如果媒体查询是一个选项,您可以为小于1000px宽的浏览器视口设置媒体查询。

假设您的HTML视口已设置:

<meta name="viewport" content="width=device-width">

你的div名为'bg':

<div class="bg"></div>

在你的CSS中:

.bg {
    width: auto; /* Scale the div to the parent width */
    height: 900px; /* The div needs some height to be visible */
    background-image: url(bg.png); /* This is your background image */
    background-size: 100%; /* Always size the image to the width of the div */
    background-position: top; /* Position the image to the top center of the div */
}

/* For any viewports less than 1000px wide */
@media (max-width: 1000px) {

    .bg {
        background-size: 1000px 600px; /* Force the image to its minimum width */
    }

}

答案 1 :(得分:4)

现在可以选择background-size 缩放图片,直到图片达到实际高度/宽度为止。这样,您就不必设置最小宽度或任何东西。

在你的CSS中:

body {
  background-size: cover;
}

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Values

答案 2 :(得分:3)

我遇到了同样的问题。以下代码对我有用。我只需要在同一个元素中添加最小宽度。在这里我只使用了html元素,我认为使用body元素更常规

     /* CSS Style Sheet */

 html    { background-image:url(example.JPG);
                    background-size:cover;
                    min-width:1000px;}

我希望这有帮助,

答案 3 :(得分:0)

您可以在calc中使用background-size

.bg {
    background-size: calc(max(100%, 1000px));
}

calc也可以与background-position一起使用,用于一侧或两侧