如何动态更改CSS中的背景高度?

时间:2017-03-27 22:16:55

标签: html css web

我正在尝试动态更改CSS中的背景高度。当我向下滚动时,我有一个背景。因此,当我使用更高的浏览器窗口时,我希望它放大我的背景,以便它下面没有间隙。我的CSS是:

body {
    min-width: 100%;
    background-image: url("Photos/Tiger-4.jpg");
    background-position: 0px 0px;
    background-size: 100%;
    background-attachment: fixed;
    background-repeat: no-repeat;
}

How it should look [Img]

What it looks like in a tall browser [Img]

在第二张图片中,您可以看到背景下方有一个白色间隙。我想让它放大图片,以便在手机上看起来不错。所以我希望背景高度与窗口高度相同,宽度要适当改变以不拉伸它。

我试过了:

background-size: auto 100%;

这只会使背景变得非常大。

感谢任何帮助:)

3 个答案:

答案 0 :(得分:0)

您可以使用vh meassure,如下所示:

div{height: 100vh;
background-image: url("http://e03-elmundo.uecdn.es/assets/multimedia/imagenes/2015/11/13/14474300157302.jpg")
}
<div>
<p>
My text
</p>
</div>

但这只是一种方式。如果这不适合您,您可以将bodyhtml设置为所需的标记height100%,您将获得类似的效果。

其他可能的选择是使用JS查找屏幕高度,然后在标签中设置所需的大小。

答案 1 :(得分:0)

Here是一个类似的演示。在背景大小上设置vh(查看高度)和cover可以解决您的问题。 article更深入一些。

div {
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    background-attachment: fixed;
    height: 90vh; // or whatever size you want it to be
}

答案 2 :(得分:0)

您可以在aspect-ratio次查询中使用@media,并根据需要更改background-position

&#13;
&#13;
body {
  background: url('http://elelur.com/data_images/mammals/tiger/tiger-06.jpg') 0 0 no-repeat;
  background-size: 100%;
}
@media (min-aspect-ratio: 3/1)  {
  body {
    background-position: center 20%;
  }
}
&#13;
&#13;
&#13;

相关问题