DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
CSS background 屬性完整整理:圖片、色彩、重複、定位與固定
編輯:CSS進階教程     

背景相關的設定雖然基礎,卻是日常開發中用到頻率最高的一組屬性。以下把 background 家族的所有成員一次整理清楚。

一、背景圖與背景色

background-image: url("圖片的網址");   /* 背景圖 */
background: url("圖片的網址");          /* 背景(簡寫) */
background-color: #色碼;               /* 背景色彩 */
background-color: transparent;          /* 設定背景為透明 */

實際寫法可以組合:

background-image: url(背景圖案.jpg);
background-color: #FFFFFF;

二、background-repeat:控制是否並排重複

值說明
repeat背景圖片向四方並排(預設值)
repeat-x背景圖片僅沿 X 軸方向並排
repeat-y背景圖片僅沿 Y 軸方向並排
no-repeat背景圖片不並排

範例:

background-image: url("https://www.webjx.com/xx.gif");
background-repeat: no-repeat;

以該圖作為背景,當圖片尺寸不足以鋪滿整個元素時,不重複填補。

三、background-attachment:背景是否隨捲動移動

值說明
scroll拉動捲軸時,背景圖片跟著移動(預設值)
fixed拉動捲軸時,背景圖片固定不動

範例:

background-image: url("https://www.webjx.com/xx.gif");
background-repeat: no-repeat;
background-attachment: fixed;

背景圖不重複並列,且不隨捲軸移動——這正是常見的「視差感」 cheap 版做法。

四、background-position:以長度或百分比定位

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 定位時最容易算錯的地方。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved