圖片是網頁內容的重要組成部分,但除了用 <img>
標籤插入圖片,還可以將圖片作為元素的背景。這能實現更豐富的視覺效果。
幾個常用的背景圖屬性:
background-image
: 設定元素的背景圖。url('圖片路徑')。background-size
: 設定背景圖的大小,cover 會將圖片縮放以完全覆蓋元素,contain 會將圖片縮放以完全包含在元素內。background-position
: 設定背景圖的位置。如 center、top、10px 20px。background-repeat
: 設定背景圖是否重複,no-repeat 常用。作品集的首頁加上一張全螢幕的背景圖,打造一種沉浸式的氛圍。
在 style.css 中:
CSS
.hero-section {
background-image: url('https://picsum.photos/1920/1080');
background-size: cover;
background-position: center;
height: 100vh; /* 讓區塊高度等於視窗高度 */
display: flex;
justify-content: center;
align-items: center;
color: white;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); /* 讓文字更清晰 */
}
這段程式碼讓 hero-section 這個區塊有了全螢幕的背景圖,並且讓背景圖隨時保持覆蓋整個區域。這在現代網頁設計中非常常見。
執行成果 :