Html 如何使用 background-size 设置最小宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16679221/
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
How to set a minimum width with background-size
提问by Gregg
I have an image that is 1000px X 600px . I want to use it as a responsive background for a div but would like to set a minimum width of 1000px despite how small the browser window is.
我有一个 1000px X 600px 的图像。我想将其用作 div 的响应式背景,但尽管浏览器窗口很小,但仍想将最小宽度设置为 1000 像素。
This is frustrating because there doesn't seem to be a simple way to define a min. width.
这令人沮丧,因为似乎没有一种简单的方法来定义最小值。宽度。
If I use background-size: cover - for some reason, the image is defaulted much larger than 1000px.
如果我使用 background-size:cover - 出于某种原因,图像默认大于 1000px。
please help
请帮忙
回答by Craig Phares
If media queries are an option, you can setup a media query for browser viewports smaller than 1000px wide.
如果媒体查询是一个选项,您可以为小于 1000px 宽的浏览器视口设置媒体查询。
Assuming your HTML viewport is set:
假设您的 HTML 视口已设置:
<meta name="viewport" content="width=device-width">
And your div is named 'bg':
你的 div 被命名为“bg”:
<div class="bg"></div>
In your CSS:
在你的 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 */
}
}
回答by Chris Barrell
There's now an option for background-size
to onlyscale the image until the picture has met it actual height/width. This way, you don't have to set a min-width or anything.
现在有一个选项background-size
可以只缩放图像,直到图片达到实际高度/宽度。这样,您不必设置最小宽度或任何东西。
In your CSS:
在你的 CSS 中:
body {
background-size: cover;
}
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Values
参考:https: //developer.mozilla.org/en-US/docs/Web/CSS/background-size#Values
回答by Maxfield Solar
I had the same problem. The following code worked for me. I just had to add a min width in the same element. Here I just used the html element, I would assume that it would be more conventional to use the body element
我有同样的问题。以下代码对我有用。我只需要在同一个元素中添加一个最小宽度。这里我只使用了 html 元素,我认为使用 body 元素会更传统
/* CSS Style Sheet */
html { background-image:url(example.JPG);
background-size:cover;
min-width:1000px;}
I hope this helps,
我希望这有帮助,
回答by Alexander Goncharov
You can use calc
in background-size
:
您可以calc
在background-size
:
.bg {
background-size: calc(max(100%, 1000px));
}
calc
works also with background-position
, for one side, or both sides
calc
也适用于background-position
, 一侧或两侧