CSS background-position 屬性
示例
如何定位背景圖片
body {
background-image: url('w3css.gif');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
}
自己動手試一試 »
更多“自己嘗試”的例子見下文。
定義和用法
background-position
屬性設定背景圖片的起始位置。
提示: 預設情況下,背景圖片放置在元素的左上角,並垂直和水平重複。
預設值 | 0% 0% |
---|---|
繼承 | no |
可動畫 | 是的。 閱讀關於可動畫的內容 嘗試一下 |
版本 | CSS1 |
JavaScript 語法 | object.style.backgroundPosition="center" 嘗試一下 |
瀏覽器支援
表中的數字指定了完全支援該屬性的第一個瀏覽器版本。
屬性 | |||||
---|---|---|---|---|---|
background-position | 1.0 | 4.0 | 1.0 | 1.0 | 3.5 |
CSS 語法
background-position: 值;
屬性值
值 | 描述 | 演示 |
---|---|---|
left top left center left bottom right top right center right bottom center top center center center bottom |
如果只指定一個關鍵字,另一個值將是“center” | 演示 ❯ |
x% y% | 第一個值是水平位置,第二個值是垂直位置。左上角是 0% 0%。右下角是 100% 100%。如果只指定一個值,另一個值將是 50%。預設值是:0% 0% | 演示 ❯ |
xpos ypos | 第一個值是水平位置,第二個值是垂直位置。左上角是 0 0。單位可以是畫素 (0px 0px) 或任何其他 CSS 單位。如果只指定一個值,另一個值將是 50%。您可以混合使用 % 和位置 | 演示 ❯ |
initial | 將此屬性設定為其預設值。閱讀關於initial | |
inherit | 從其父元素繼承此屬性。閱讀關於inherit |
更多示例
示例
如何將背景圖片定位在頂部居中
body {
background-image: url('w3css.gif');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
}
自己動手試一試 »
示例
如何將背景圖片定位在右下角
body {
background-image: url('w3css.gif');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: bottom right;
}
自己動手試一試 »
示例
如何使用百分比定位背景圖片
body {
background-image: url('w3css.gif');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50% 50%;
}
自己動手試一試 »
示例
如何使用畫素定位背景圖片
body {
background-image: url('w3css.gif');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50px 150px;
}
自己動手試一試 »
示例
使用不同的背景屬性建立“英雄”圖片
.hero-image {
background-image: url("photographer.jpg"); /* 使用的圖片 */
background-color: #cccccc; /* 如果圖片不可用時使用 */
height: 500px; /* 您必須指定高度 */
background-position: center; /* 居中圖片 */
background-repeat: no-repeat; /* 不重複圖片 */
background-size: cover; /* 將背景圖片縮放到覆蓋整個容器 */
}
自己動手試一試 »
相關頁面
CSS 教程:CSS 背景
CSS 參考: background-image 屬性
HTML DOM 參考: backgroundPosition 屬性