HTML 背景圖片
幾乎任何 HTML 元素都可以指定背景圖片。
HTML 元素的背景圖片
要為 HTML 元素新增背景圖片,請使用 HTML 的 style
屬性和 CSS 的 background-image
屬性。
您也可以在 <head>
部分的 <style>
元素中指定背景圖片。
頁面背景圖片
如果您想讓整個頁面都有背景圖片,則必須在 <body>
元素上指定背景圖片。
背景重複
如果背景圖片比元素小,圖片將水平和垂直地重複自身,直到到達元素的末尾。
要避免背景圖片重複,請將 background-repeat
屬性設定為 no-repeat
。
示例
<style>
body {
background-image: url('example_img_girl.jpg');
background-repeat: no-repeat;
}
</style>
自己動手試一試 »
背景覆蓋
如果您希望背景圖片覆蓋整個元素,可以將 background-size
屬性設定為 cover.
。
此外,為了確保整個元素始終被覆蓋,請將 background-attachment
屬性設定為 fixed:
。
這樣,背景圖片將覆蓋整個元素,而不會拉伸(圖片將保持其原始比例)。
示例
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
自己動手試一試 »
背景拉伸
如果您希望背景圖片拉伸以適應整個元素,可以將 background-size
屬性設定為 100% 100%
。
嘗試調整瀏覽器視窗的大小,您會看到圖片會拉伸,但始終覆蓋整個元素。
示例
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
</style>
自己動手試一試 »
瞭解更多 CSS
從上面的示例中,您已經瞭解到背景圖片可以透過 CSS 的 background 屬性進行樣式設定。
要了解更多關於 CSS background 屬性的資訊,請學習我們的 CSS 背景教程。