CSS background-position-x 屬性
定義和用法
background-position-x
屬性設置背景圖像在 x 軸上的位置。
提示:默認情況下,背景圖像放置在元素的左上角,并在垂直和水平方向上重復。
實例
例子 1
如何在 x 軸上定位背景圖像:
div { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: center; }
例子 2
如何將背景圖像定位到右側:
body { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: right; }
例子 3
如何使用百分比定位背景圖像:
body { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: 50%; }
例子 4
如何使用像素定位背景圖像:
body { background-image: url('w3css.gif'); background-repeat: no-repeat; background-position-x: 150px; }
例子 5
使用不同的背景屬性創建一個覆蓋其容器的背景圖像:
.hero-image { background-image: url("photographer.jpg"); /* 使用的圖像 */ background-color: #cccccc; /* 如果圖像不可用,則使用此顏色 */ height: 300px; /* 必須設置高度 */ background-position-x: center; /* 將圖像居中 */ background-repeat: no-repeat; /* 不重復圖像 */ background-size: cover; /* 調整背景圖像大小以覆蓋整個容器 */ }
CSS 語法
background-position-x: value;
屬性值
值 | 描述 |
---|---|
left | 將背景定位在 x 軸的左側。 |
right | 將背景定位在 x 軸的右側。 |
center | 將背景定位在 x 軸的中心。 |
x% |
x 軸的左側為 0%,右側為 100%。 百分比值指的是背景定位區域的寬度減去背景圖像的寬度。 |
xpos | 距離左側的水平距離。單位可以是像素(如 0px)或其他 CSS 單位。 |
xpos offset |
雙值語法,僅在 Firefox 和 Safari 中支持。
單位可以是像素或其他 CSS 單位。 |
initial | 將此屬性設置為其默認值。參閱 initial。 |
inherit | 從其父元素繼承此屬性。參閱 inherit。 |
技術細節
默認值: | 0% |
---|---|
繼承性: | 否 |
動畫制作: | 支持。請參閱:動畫相關屬性。 |
版本: | CSS3 |
JavaScript 語法: | object.style.backgroundPositionX="center" |
瀏覽器支持
表格中的數字表示首個完全支持該屬性的瀏覽器版本。
Chrome | Edge | Firefox | Safari | Opera | |
---|---|---|---|---|---|
單值語法 | 1.0 | 12.0 | 49.0 | 1.0 | 15.0 |
雙值語法 | 不支持 | 不支持 | 49.0 | 15.4 | 不支持 |
相關頁面
教程:CSS 背景
CSS 參考:background-image 屬性
CSS 參考:background-position 屬性
CSS 參考:background-position-y 屬性
HTML DOM 參考:backgroundPosition 屬性