background-position-x
Baseline 廣泛可用 *
background-position-x CSS 屬性設定每個背景影像的初始水平位置。該位置相對於由 background-origin 設定的位置層。
試一試
background-position-x: left;
background-position-x: center;
background-position-x: 25%;
background-position-x: 2rem;
background-position-x: right 32px;
<section class="display-block" id="default-example">
<div class="transition-all" id="example-element"></div>
</section>
#example-element {
background-color: navajowhite;
background-image: url("/shared-assets/images/examples/star.png");
background-repeat: no-repeat;
height: 100%;
}
此屬性的值將被在它之後應用於元素的 background 或 background-position 簡寫屬性的任何宣告覆蓋。
語法
css
/* Keyword values */
background-position-x: left;
background-position-x: center;
background-position-x: right;
/* <percentage> values */
background-position-x: 25%;
/* <length> values */
background-position-x: 0px;
background-position-x: 1cm;
background-position-x: 8em;
/* Side-relative values */
background-position-x: right 3px;
background-position-x: left 25%;
/* Multiple values */
background-position-x: 0px, center;
/* Global values */
background-position-x: inherit;
background-position-x: initial;
background-position-x: revert;
background-position-x: revert-layer;
background-position-x: unset;
background-position-x 屬性指定為一個或多個值,用逗號分隔。
值
left-
將背景影像的左邊緣與背景位置層的左邊緣對齊。
center-
將背景影像的中心與背景位置層的中心對齊。
right-
將背景影像的右邊緣與背景位置層的右邊緣對齊。
<length>-
給定背景影像的左垂直邊緣相對於背景位置層的左垂直邊緣的偏移量。(一些瀏覽器允許指定右邊緣作為偏移量)。
<percentage>-
給定背景影像的水平位置相對於容器的偏移量。值為 0% 表示背景影像的左邊緣與容器的左邊緣對齊,值為 100% 表示背景影像的右邊緣與容器的右邊緣對齊,因此 50% 的值會使背景影像水平居中。
正式定義
| 初始值 | 0% |
|---|---|
| 應用於 | 所有元素。也適用於 ::first-letter 和 ::first-line。 |
| 繼承性 | 否 |
| 百分比 | 指背景定位區域的寬度減去背景影像的寬度 |
| 計算值 | 一個列表,每個專案由以下部分組成:由絕對長度和百分比組合給出的偏移量,加上一個原點關鍵詞 |
| 動畫型別 | 一個可重複的列表 |
正式語法
background-position-x =
[ center | [ [ left | right | x-start | x-end ]? <length-percentage>? ]! ]#
<length-percentage> =
<length> |
<percentage>
示例
基本示例
以下示例顯示了背景影像的實現,其中 background-position-x 和 background-position-y 用於分別定義影像的水平和垂直位置。
HTML
html
<div></div>
CSS
css
div {
width: 300px;
height: 300px;
background-color: skyblue;
background-image: url("https://mdn.dev/archives/media/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png");
background-repeat: no-repeat;
background-position-x: center;
background-position-y: bottom;
}
結果
與邊相關的數值
以下示例顯示了對與邊相關的偏移語法 (side-relative offset syntax) 的支援,該語法允許開發人員將背景從任何邊緣偏移。
HTML
html
<div></div>
CSS
css
div {
width: 300px;
height: 300px;
background-color: seagreen;
background-image: url("https://mdn.dev/archives/media/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png");
background-repeat: no-repeat;
background-position-x: right 20px;
background-position-y: bottom 10px;
}
結果
規範
| 規範 |
|---|
| CSS 背景模組第 4 級 # background-position-longhands |
瀏覽器相容性
載入中…