- **注意點1:**如果你的背景圖檔和浏覽器可視區背景色(透明/白色)是一緻的(區分不開),就需要自己給這個盒子設定非白色的背景顔色來襯托出你的背景圖檔;如果背景圖檔裡面有其他顔色就不用考慮這個。
-
**注意點2:**因為background是一個簡寫屬性,裡面包含background-color,是以如果同時設定了這兩個屬性,注意它們的層疊性問題。
( 說明:我這裡使用的背景圖檔是小米的白色圖示,和我的浏覽器背景色是一緻的。)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.logo {
width: 55px;
height: 55px;
background-color: #ff6700;
background: url(images/mi-logo.png) no-repeat center;
}
</style>
</head>
<body>
<div class="logo"></div>
</body>
</html>
顯示效果:白茫茫一片,啥都看不見…
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxczMxATNwIjMxEjMxAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
通過浏覽器審查元素:
我們發現,雖然background裡面我們隻指定了背景圖檔URL、平鋪方式、圖檔位置沒有設定顔色,但根據background裡的最後一句background-color:#ff6700; 可以知道我們先前單獨設定的background-color: #ff6700;無效了,因為它被後面background裡面的background-color的預設值 transparent給層疊掉了,浏覽器和背景圖的顔色一緻,是以當然看不見裡面插入的背景圖檔了!
是以我們換一下background-color和background的順序,用橙色來層疊掉透明色,那自然能看到我們白色的背景圖檔啦!
.logo {
width: 55px;
height: 55px;
background: url(images/mi-logo.png) no-repeat center;
background-color: #ff6700;
}
效果圖:
當然如果直接在background裡面設定我們想要的background-color而不分開寫,自然不用考慮層疊性問題啦!
.logo {
width: 55px;
height: 55px;
background: #ff6700 url(images/mi-logo.png) no-repeat center;
}