背景相關的設定雖然基礎,卻是日常開發中用到頻率最高的一組屬性。以下把 background 家族的所有成員一次整理清楚。
background-image: url("圖片的網址"); /* 背景圖 */
background: url("圖片的網址"); /* 背景(簡寫) */
background-color: #色碼; /* 背景色彩 */
background-color: transparent; /* 設定背景為透明 */
實際寫法可以組合:
background-image: url(背景圖案.jpg); background-color: #FFFFFF;
| 值 | 說明 |
|---|---|
repeat | 背景圖片向四方並排(預設值) |
repeat-x | 背景圖片僅沿 X 軸方向並排 |
repeat-y | 背景圖片僅沿 Y 軸方向並排 |
no-repeat | 背景圖片不並排 |
範例:
background-image: url("https://www.webjx.com/xx.gif");
background-repeat: no-repeat;
以該圖作為背景,當圖片尺寸不足以鋪滿整個元素時,不重複填補。
| 值 | 說明 |
|---|---|
scroll | 拉動捲軸時,背景圖片跟著移動(預設值) |
fixed | 拉動捲軸時,背景圖片固定不動 |
範例:
background-image: url("https://www.webjx.com/xx.gif");
background-repeat: no-repeat;
background-attachment: fixed;
背景圖不重複並列,且不隨捲軸移動——這正是常見的「視差感」 cheap 版做法。
background-position: x y; /* 以長度定位 */ background-position: x% y%; /* 以百分比定位 */
其中 x% 往右移、y% 往下移。九宮格對照如下:
background-position: 0% 0%; /* 左上 */ background-position: 0% 50%; /* 左中 */ background-position: 50% 0%; /* 中上 */ background-position: 50% 50%; /* 正中央 */ background-position: 100% 0%; /* 右上 */ background-position: 0% 100%; /* 左下 */ background-position: 100% 50%; /* 右中 */ background-position: 50% 100%; /* 中下 */ background-position: 100% 100%; /* 右下 */
| 關鍵字 | 說明 |
|---|---|
top | 上(y = 0) |
center | 中(x = 50%,y = 50%) |
bottom | 下(y = 100%) |
left | 左(x = 0) |
範例:
background-position: center; /* 置中 */ background-position: 200px 30px; /* 距左 200px、距上 30px */
以上屬性都可以合併成一行使它更精簡:
background: #FFF url("bg.gif") no-repeat fixed 200px 30px;
順序是「色彩-圖片-重複-attachment-位置」。使用簡寫時有個要注意的地方:未寫出的屬性會被重設為預設值,所以若先前已另外設定過 background-position,再用簡寫就會把它清掉。
另外提醒一點,background-position 的百分比是「圖片本身的百分比點」對齊「容器的百分比點」,跟直觉中以為的「從左上角算起」不同。例如 50% 50% 剛好置中,但 25% 25% 並不是容器的四分之一處——這也是 CSS sprite 定位時最容易算錯的地方。