CSS從入門到精通——背景樣式

背景色

我們可以使用background-color爲元素設置背景色,通常屬性值爲顏色名稱或顏色編碼。

因爲HTML文檔中body元素包含了HTML文檔的所有內容,所以如果要改變整個頁面的背景顏色,只需要設置body元素的background-color屬性。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello World</title>
  <style type="text/css">
    body {
       background-color: lightyellow;
    }
    h1 {
      color: gray;
      background-color: palegreen;
    }
    p {
      background-color: lightgray;
    }
  </style>
</head>
<body>
  <div>
    <h1>CSS讓網頁樣式更豐富</h1>
    <p>這是一個段落</p>
  </div>
</body>
</html>

顯示效果如下: 

背景圖片

設置背景圖片

我們可以使用background-image屬性設置元素的背景屬性,常見的網頁背景圖就是這樣設置的。其中,屬性值通過url指定圖片鏈接。

書寫格式:

background-image: url("圖片鏈接")

 

平鋪背景圖像

指定了背景圖像之後,默認背景圖是平鋪重複顯示。如果想要設置圖像在水平方向、垂直方向平鋪或其他方式,可以設置background-repeat屬性。

具體屬性值設置如下:

樣式 屬性值
水平平鋪重複 repeat-x
垂直平鋪重複 repeat-y
不重複平鋪 no-repeat

例如:

默認平鋪

body {
     /*設置背景圖片*/
     background-image:url("./Assert/sun.jpg");
 }

repeat-x 

body {
     /*設置背景圖片*/
     background-image:url("./Assert/sun.jpg");
     background-repeat: repeat-x;
 }

repeat-y

body {
     /*設置背景圖片*/
     background-image:url("./Assert/sun.jpg");
     background-repeat: repeat-y;
 }

no-repeat

body {
     /*設置背景圖片*/
     background-image:url("./Assert/sun.jpg"); 
     background-repeat: no-repeat;
 }

背景定位與背景關聯 

背景定位

當圖像作爲背景和文本顯示在同一個位置時,爲了頁面排版更優美、更易於文本的閱讀,我們可以使用background-position屬性改變圖像在背景中的位置:

舉例如下:

body {
    /*設置背景圖片*/
    background-image: url("https://www.educoder.net/attachments/download/211104");
    background-repeat: no-repeat;
    background-position: right top;
}
後序見下篇
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章