【问题标题】:How to set a minimum width with background-size如何使用背景大小设置最小宽度
【发布时间】:2020-05-13 02:23:21
【问题描述】:

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

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

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

请帮忙

【问题讨论】:

  • 必须尝试在以您的图像为背景的父元素上定义最小宽度?然后你的其余内容可以进入其中。
  • 我做了,但它不起作用。
  • “background-size:cover”好像是用标签的高度来决定图片的宽度。这太愚蠢了。为什么不使用div的设置高度?
  • 你的意思是 max-width 不是 min-width,对吗?!或者你的最后一句话没有意义:图像默认大于 1000px。
  • 你有一些html要发布吗?你的背景尺寸在身体上吗?

标签: html css


【解决方案1】:

如果可以选择媒体查询,您可以为宽度小于 1000 像素的浏览器视口设置媒体查询。

假设您的 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 */
    }

}

【讨论】:

  • 请注意,不要伪造使用前缀Reference.
  • 我宁愿在媒体查询一中使用background-size: initial。 :D
【解决方案2】:

现在background-size 可以选择缩放图像,直到图片达到实际高度/宽度。这样,您不必设置最小宽度或任何其他内容。

在您的 CSS 中:

body {
  background-size: cover;
}

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

【讨论】:

  • background-size: cover 不会在图像的实际大小处停止缩小
【解决方案3】:

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

     /* CSS Style Sheet */

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

希望对你有帮助,

【讨论】:

    【解决方案4】:

    您可以在background-size 中使用calc

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 2014-08-04
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 2015-03-31
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多