background-position-x

Baseline 廣泛可用 *

此特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 ⁨2016 年 9 月⁩以來,它已在各大瀏覽器中可用。

* 此特性的某些部分可能存在不同級別的支援。

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%;
}

此屬性的值將被在它之後應用於元素的 backgroundbackground-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

將背景影像的中心與背景位置層的中心對齊。

將背景影像的右邊緣與背景位置層的右邊緣對齊。

<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

瀏覽器相容性

另見