CSS @property - inherits



如果使用 `@property` at-rule,則必須包含 CSS 描述符 `inherits`。

它決定了 `@property` 定義的自定義屬性註冊預設是否繼承。

可能的值

  • true - 屬性預設繼承。

  • false - 屬性預設不繼承。

語法

inherits = true | false 

CSS inherits - border-color

以下程式碼是 `inherits` 描述符的示例。

  • 在以下使用 `@property` 的示例中,該描述符定義了一個自定義屬性 `--theme-color`,並配置為 `inherits: true;`。

  • 這允許定義的 `--theme-color` 在整個 DOM 層次結構中繼承其值,確保 `.container` 內的元素繼承此屬性的文字和背景顏色。

  • 指定的 `--theme-color` 被 `.title`、`.text` 和 `.nested-text` 元素繼承,確保巢狀結構中的文字顏色和背景保持一致。

<html>
<head>
<style>
   @property --theme-color {
      syntax: '<color>';
      inherits: true; /* Specifies that this property should inherit its value */
      initial-value: black; /* Default color if not explicitly set */
   }
   /* Apply the custom property to style elements */
   .container {
      --theme-color: red; /* Set a custom color for the container */
   }
   .title,
   .text,
   .nested-text {
      color: var(--theme-color); /* Inherit theme color for text */
      background-color: #f7f7f7; /* Set a light background color */
      padding: 10px;
      margin: 5px 0;
   }
   .title {
      font-size: 24px;
   }
</style>
</head>
<body>
   <div class="container">
      <div class="header">
         <h1 class="title">Custom Properties Example</h1>
      </div>
      <div class="content">
         <p class="text">This text inherits the theme color for text and background.</p>
         <div class="nested">
         <p class="nested-text">Nested text inherits the same theme color!</p>
         </div>
      </div>
   </div>
</body>
</html>
   
廣告
© . All rights reserved.