背景位置屬性用於設定背景圖像的落點,它只能套用在塊級元素與替換元素上。其中替換元素包括 img、input、textarea、select 與 object。
語法:
background-position:像素值/關鍵字;
說明:
取值有兩種方式:一是使用像素值,二是使用關鍵字描述。
使用像素值時,需要同時給出水平方向(x 軸)與垂直方向(y 軸)的數值。例如「background-position:12px 24px;」表示背景圖片距元素左上角水平 12px、垂直 24px。兩個值之間以空格隔開。
| 設置值 | 說明 |
|---|---|
| x(數值) | 設置橫向位置,單位為 px |
| y(數值) | 設置縱向位置,單位為 px |
入門階段一律使用像素作單位,其他 CSS 單位留到進階階段再深入。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>background-position屬性</title>
<style type="text/css">
#div1 { width:400px; height:300px; border:1px solid gray; background-image:url("../App_images/lesson/run_cj/one piece.jpg"); background-repeat:no-repeat; background-position:80px 40px; }
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
在瀏覽器中預覽,效果如下:
註:預覽圖中的紅色字體為註解,方便讀者理解。
分析:
本例為 id="div1" 的元素設定了寬高與邊框,讓容器範圍看得清楚。
關鍵點在於:background-position 的水平與垂直距離,是相對於該元素的左上角計算的。對照預覽圖仔細看,這個基準點就好理解了。
使用關鍵字時,同樣需要給出水平與垂直兩個方向的值,只是不用 px 數值,改用英文關鍵字表示。
| 屬性值 | 說明 |
|---|---|
| top left | 左上 |
| top center | 靠上居中 |
| top right | 右上 |
| left center | 靠左居中 |
| center center | 正中 |
| right center | 靠右居中 |
| bottom left | 左下 |
| bottom center | 靠下居中 |
| bottom right | 右下 |
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>background-position屬性</title>
<style type="text/css">
#div1 { width:240px; height:160px; border:1px solid gray; background-image:url("../App_images/lesson/run_cj/cartoongirl.gif"); background-repeat:no-repeat; background-position:right center; }
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
在瀏覽器中預覽,效果如下:
分析:
「background-position:right center;」中,right 表示水平方向靠右,center 表示垂直方向居中。另外因為使用的是 gif 動態圖片,你在瀏覽器中還會看到圖片正在播放。