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

Gre*_*egg 11 css html5 css3

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

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

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

请帮忙

Cra*_*res 18

如果选择媒体查询,则可以为小于1000px宽的浏览器视口设置媒体查询.

假设您的HTML视口已设置:

<meta name="viewport" content="width=device-width">
Run Code Online (Sandbox Code Playgroud)

而你的div被命名为'bg':

<div class="bg"></div>
Run Code Online (Sandbox Code Playgroud)

在你的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 */
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 只是注意,不要伪造使用_prefixes_.[参考文献](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size). (2认同)
  • 我宁愿在媒体查询中使用“background-size: initial”。:D (2认同)

小智 5

现在有一个选项background-size可以缩放图像,直到图片达到其实际的高度/宽度为止。这样,您无需设置最小宽度或其他任何内容。

在您的CSS中:

body {
  background-size: cover;
}
Run Code Online (Sandbox Code Playgroud)

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


Ale*_*rov 5

您可以使用calcbackground-size

.bg {
    background-size: calc(max(100%, 1000px));
}
Run Code Online (Sandbox Code Playgroud)

calc也适用于background-position一侧或两侧