background-image
屬性來設置。你可以根據需要調整背景圖片的大小、重復方式、位置等。css復制代碼/* styles.css */.background-container { width: 100%; height: 400px; /* 設置容器高度 */ background-image: url('https://example.com/image.jpg'); /* 背景圖片的URL */ background-size: cover; /* 將背景圖像等比縮放以完全覆蓋容器 */ background-position: center; /* 背景圖像居中顯示 */ background-repeat: no-repeat; /* 禁止背景圖片重復 */}
background-image
: 設置背景圖片的 URL,指向需要用作背景的圖片的路徑或 URL。
background-size
:
cover
: 背景圖像將會按比例縮放,以完全覆蓋容器,不會有空白區域,但可能部分圖像會被裁剪。
contain
: 背景圖像將按比例縮放,以完全適應容器,整個圖像都會顯示,但可能會有空白區域。
background-position
: 設置背景圖像的顯示位置。
center
: 背景圖像居中顯示。
top
, bottom
, left
, right
: 設置具體顯示方位。
background-repeat
: 設置背景圖像是否重復。
no-repeat
: 不重復背景圖像。
repeat
: 背景圖像會在水平方向和垂直方向重復。
repeat-x
: 只在水平方向重復。
repeat-y
: 只在垂直方向重復。
html復制代碼<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>背景圖片示例</title> <link rel="stylesheet" href="styles.css"></head><body> <div class="background-container"> <h1>這是一個帶背景圖片的容器</h1> <p>這里是一些文本內容</p> </div></body></html>
css復制代碼/* styles.css */body { margin: 0; padding: 0; font-family: Arial, sans-serif; }.background-container { width: 100%; height: 400px; background-image: url('https://example.com/image.jpg'); /* 替換成你實際的圖片URL */ background-size: cover; background-position: center; background-repeat: no-repeat; color: white; /* 設置文字顏色 */ display: flex; justify-content: center; align-items: center; text-align: center; }
background-image: url(...)
:指定背景圖片的路徑或 URL。
background-size: cover
:讓圖片覆蓋整個背景區域。
background-position: center
:使背景圖片居中顯示。
background-repeat: no-repeat
:防止背景圖片重復。
該代碼會創建一個容器,背景為指定的圖片,文本內容居中顯示且不被背景圖片遮擋。你可以根據需求調整相關的 CSS 屬性以獲得不同的效果。