根据容器Div调整背景图像的大小

本文关键字:图像 背景 调整 Div | 更新日期: 2023-09-27 18:18:17

我有一个像image.jpg的背景图像。我想根据使用它的div来调整图片的大小。

根据容器Div调整背景图像的大小

有许多不同的方法可以做到这一点。在执行速度方面最好的是使用CSS,但jQuery可以完成任何CSS可以使用$().css()方法。

这里有四种不同的方法,从仅仅放入图像,到在css和jQuery中拉伸。代码如下:

<style>
div
{
    background-image : url("http://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Les_Halles_%28metro_de_Paris%29_-_Entree.jpg/800px-Les_Halles_%28metro_de_Paris%29_-_Entree.jpg");
    height : 200px;
    width: 200px;
    margin: 10px;
    background-repeat : no-repeat;
    background-color: blue;
    float: left;
}
#one
{
    background-size:contain;
}
#two
{
    background-size: 100%;
}
#three
{
    background-size: 100% 100%;
}

</style>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
<script>
    $("#a").css("background-size","contain") //fits in aspect ratio
    $("#b").css("background-size","100%") //constrained by width
    $("#c").css("background-size","100% 100%") //stretch to fill
    $("#d").css("background-size","auto 100%") //constrained by height
</script>

希望这能对这个问题有所帮助。

这里有一些很好的CSS参考资料,如果你想探索属性,看看还有什么可以做的