CSS3 背景樣式

background-size 指定背景圖片大小

background-size: auto | length | percentage | cover | contain

CSS 指定背景圖片大小 lengthpercentage 百分比可設定兩數值,也可只設定一個數值。當只設定一個數值,另一個數值(高)預設值為 auto 此時高度以背景圖原始寬高比例,自動縮放。

  • auto 為預設值,即背景圖片原始長寬。
  • length 指定圖片具體大小的數值,不允許負值。
  • percentage 以背景圖所在元素的百分比指定背景圖大小(不允許負值)。
  • cover 主要用於背景圖小於所在的容器,而背景圖又不適合使用 repeat,此時就可以採用 cover 的方式,使背景圖放大至容器的大小,但此方法容易使背景圖因放大而失真。
  • containcover 正好相反,主要用於背景圖大於所在容器,但卻需要將背景圖完整呈現,此時就可採用 contain 的方式,使背景圖縮小至容器的大小。
background:url(penguin.png) no-repeat center;
background-size: auto;
background-size: 300px 100px;
background-size: cover; /*以寬度縮放*/
background-size: contain; /*以高度縮放*/


background-blend-mode 背景混合模式

定義該元素的背景圖片,以及背景顏色混合方式。指的是單一元素指定兩個背景屬性,例如同時有「漸層顏色」及「背景圖片」或兩張圖像用 background-blend-mode 混合模式效果。與下層元素沒有關係。

div{background:url(cherry-blossom.jpg) no-repeat,
    linear-gradient(90deg, #ff9ce4, #a3a129);
    background-blend-mode:multiply;}

normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity


mix-blend-mode 背景混合模式

mix-blend-mode:multiply;

CSS mix-blend-mode 元素的內容與元素的直系父元素「下一層」的混合方式。類似 Photoshop 的圖層混合模式,與下一層元素有關係同樣貝有十六項的混合方式。混和對象為元素的背景圖片以及背景色、漸層顏色。





Multiple background 多張圖片背景

單一元素可以同時指定置放多張圖片當作背景,每組屬性間使用「逗號」分隔,先讀取的背景圖會附蓋在後寫入的背景圖之上,所以順序需安排一下。置放多張圖片有另一個圖片屬性問題 CSS 的 background 屬性的縮寫順序。

background-color background-image background-repeat background-attachment background-position background-size 使用 background-size 時需要加上 / 分隔。

可以配合圖片背景屬性安排
background-image | background-repeat | background-attachment | background-position | background-origin | background-clip | background-size

div{background:url(firebug.png) no-repeat 200px 100px,
    url(cherry-blossom.jpg) no-repeat scroll top left / cover;}




CSS 背景樣式

background 使用縮寫語法

background:red no-repeat url("dotUi.png");
background:red no-repeat url("dotUi.png");background-position:60% -40%;
background:url(dotUi.png) repeat-x scroll 0 0 rgba(0,0,0,0.3); /*可省去圖片雙引號*/

background-position 位置語法 (x% y% 前面是水平位置、後面是垂直位置)

背景屬性元素的矩框之背景圖 background-position 沒有設定時,其背景圖的初始預設位置於元素矩框左上角。

  • percentage 百分比表示
  • 可用兩個百分比表示水平與垂直的起點。
    只用一個百分比表示水平位置,垂直位置由系統預設值是 50% (亦可用負值)。
  • length 長度值表示
  • 可用兩個長度值表示水平與垂直的起點。單位是圖元 0px 0px 或任何其他的 CSS 單位。
    可以混合使用 %length 值。
  • top, center, bottom 位置方向表示
  • 使用此方法背景圖只顯示於元素的矩框之內,其參數有 left, center, right … 及下列方式。

  • top left
  • top center
  • top right
  • center left
  • center center
  • center right
  • bottom left
  • bottom center
  • bottom right

background-repeat 背景圖是否要重複

  • repeat
  • 背景圖在水平與垂直重複 (此為預設值)。
  • repeat-x
  • 背景圖只在水平重複。
  • repeat-y
  • 背景圖只在垂直重複。
  • no-repeat
  • 背景圖不重複,只排列一次。

background-attachment 背景圖固定或者隨著頁面的內容滾動

  • scroll
  • 背景圖像會隨著頁面其餘部分的滾動而移動 (此為預設值)。
  • fixed
  • 當頁面的其餘部分滾動時,背景圖像不會移動。
  • inherit
  • 繼承父元件所設之特徵。

SVG as Background Images

background-image:url("images/charts.svg");
background-size:300px 100px;
width:300px;
height:100px;