Latest web development tutorials

CSS Backgrounds(背景)

CSS 背景屬性用於定義HTML元素的背景。

CSS 屬性定義背景效果:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

背景顏色

background-color 屬性定義了元素的背景顏色.

頁面的背景顏色使用在body的選擇器中:

實例

body {background-color:#b0c4de;}

嘗試一下»

CSS中,顏色值通常以以下方式定義:

  • 十六進制- 如:"#ff0000"
  • RGB - 如:"rgb(255,0,0)"
  • 顏色名稱- 如:"red"

以下實例中, h1, p, 和div 元素擁有不同的背景顏色:

實例

h1 {background-color:#6495ed;}
p {background-color:#e0ffff;}
div {background-color:#b0c4de;}

嘗試一下»


背景圖像

background-image 屬性描述了元素的背景圖像.

默認情況下,背景圖像進行平鋪重複顯示,以覆蓋整個元素實體.

頁面背景圖片設置實例:

實例

body {background-image:url('paper.gif');}

嘗試一下»

下面是一個例子是一個糟糕的文字和背景圖像組合。 文本可讀性差:

實例

body {background-image:url('bgdesert.jpg');}

嘗試一下»


背景圖像- 水平或垂直平鋪

默認情況下background-image 屬性會在頁面的水平或者垂直方向平鋪。

一些圖像如果在水平方向與垂直方向平鋪,這樣看起來很不協調,如下所示:

實例

body
{
background-image:url('gradient2.png');
}

嘗試一下»

如果圖像只在水平方向平鋪(repeat-x), 頁面背景會更好些:

實例

body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}

嘗試一下»


背景圖像- 設置定位與不平鋪

Remark 讓背景圖像不影響文本的排版

如果你不想讓圖像平鋪,你可以使用background-repeat 屬性:

實例

body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
}

嘗試一下»

以上實例中,背景圖像與文本顯示在同一個位置,為了讓頁面排版更加合理,不影響文本的閱讀,我們可以改變圖像的位置。

可以利用background-position 屬性改變圖像在背景中的位置:

實例

body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
}

嘗試一下»


背景- 簡寫屬性

在以上實例中我們可以看到頁面的背景顏色通過了很多的屬性來控制。

為了簡化這些屬性的代碼,我們可以將這些屬性合併在同一個屬性中.

背景顏色的簡寫屬性為"background":

實例

body {background:#ffffff url('img_tree.png') no-repeat right top;}

嘗試一下»

當使用簡寫屬性時,屬性值的順序為::

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

以上屬性無需全部使用,你可以按照頁面的實際需要使用.

這個實例使用了先前介紹的CSS,你可以查看相應實例: CSS實例


Examples

更多實例

如何設置固定的背景圖像
本例演示如何設置固定的背景圖像。 圖像不會隨著頁面的其他部分滾動。


CSS 背景屬性

Property 描述
background 简写属性,作用是将背景属性设置在一个声明中。
background-attachment 背景图像是否固定或者随着页面的其余部分滚动。
background-color 设置元素的背景颜色。
background-image 把图像设置为背景。
background-position 设置背景图像的起始位置。
background-repeat 设置背景图像是否及如何重复。