background-origin

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

background-origin CSS 屬性設定背景圖片的起始位置:從邊框的起點開始,在邊框內部,或者在內邊距內部。

試一試

background-origin: border-box;
background-repeat: no-repeat;
background-origin: padding-box;
background-repeat: no-repeat;
background-origin: content-box;
background-repeat: no-repeat;
<section id="default-example">
  <div id="example-element">This is the content of the element.</div>
</section>
#example-element {
  background-image: url("/shared-assets/images/examples/leopard.jpg");
  color: #d73611;
  text-shadow: 2px 2px black;
  padding: 20px;
  border: 10px dashed #333333;
  font-size: 2em;
  font-weight: bold;
}

請注意,當 background-attachmentfixed 時,background-origin 將被忽略。

語法

css
/* Keyword values */
background-origin: border-box;
background-origin: padding-box;
background-origin: content-box;

/* Global values */
background-origin: inherit;
background-origin: initial;
background-origin: revert;
background-origin: revert-layer;
background-origin: unset;

background-origin 屬性的值為下面列出的關鍵字之一。

border-box

背景相對於邊框盒定位。

padding-box

背景相對於內邊距盒定位。預設值。

content-box

背景相對於內容盒定位。

正式定義

初始值padding-box
應用於所有元素。也適用於 ::first-letter::first-line
繼承性
計算值同指定值
動畫型別一個可重複的列表

正式語法

background-origin = 
<visual-box>#

<visual-box> =
content-box |
padding-box |
border-box

示例

設定背景起點

css
.example {
  border: 10px double;
  padding: 10px;
  background: url("image.jpg");
  background-position: center left;
  background-origin: content-box;
}
css
#example2 {
  border: 4px solid black;
  padding: 10px;
  background: url("image.gif");
  background-repeat: no-repeat;
  background-origin: border-box;
}
css
div {
  background-image:
    url("logo.jpg"), url("main-back.png"); /* Applies two images to the background */
  background-position:
    top right,
    0px 0px;
  background-origin: content-box, padding-box;
}

使用兩個漸變

在此示例中,該盒子有一個粗虛線邊框。第一個漸變使用 padding-box 作為 background-origin,因此背景位於邊框內部。第二個漸變使用 content-box,因此只顯示在內容後面。

css
.box {
  margin: 10px 0;
  color: white;
  background:
    linear-gradient(
      90deg,
      rgb(131 58 180 / 100%) 0%,
      rgb(253 29 29 / 60%) 60%,
      rgb(252 176 69 / 100%) 100%
    ),
    radial-gradient(circle, white 0%, black 28%);
  border: 20px dashed black;
  padding: 20px;
  width: 400px;
  background-origin: padding-box, content-box;
  background-repeat: no-repeat;
}
html
<div class="box">Hello!</div>

規範

規範
CSS Backgrounds and Borders Module Level 3
# background-origin

瀏覽器相容性

另見