編碼的世界 / 優質文選 / 生涯

css中設置多張背景圖片


2021年10月01日
-   

有一些應用場景中,我們需要疊加設置多張圖片,一般我們可能是采用img來設置,但還有一種更簡單的方法,采用背景屬性來設置,css提供了可同時設置多張背景圖的屬性。語法如下:
.bg{
background:
url('../img/bg1.png'),
url('../img/bg2.png'),
url('../img/bg3.png')
}

為不同的背景圖片設置大小和位置:
.bg{
height:100%;
width:100%;
background:
url('../img/bg1.png'),
url('../img/bg2.png'),
url('../img/bg3.png');
background-size:75%,50%,cover;
background-position:top50px right 80px,40px 40px,top center;
background-repeat:no-repeat;
}

設置background-size和position屬性時,按照背景的顯示順序進行設置。背景圖片最先設置的圖片顯示在最上面,最後設置的圖片顯示在最下面。
另外背景可以混合設置:比如你可以同時設置圖片和背景色,很多時候我們開發中會遇到以下這種效果,使用這種方法可以最快搞定,而且不用再考慮適配性問題。

實現代碼:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>An example</title>
<meta name="viewport" content="width=device-width">
<style>
html,body {
margin: 0;
padding: 0;
}
.bg-multi {
height: 100vh;
width: 100vw;
background:
url('icon-empty.png'),#FAFAFA;
background-size:30vw, cover;
background-position:center,center;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div class="bg-multi"></div>
</body>
</html>

 

熱門文章