CSS - @property



作為 CSS Houdini API 的一部分,@property CSS @規則允許開發者顯式定義自定義屬性。

@property 規則

  • 提供諸如屬性型別檢查、約束、設定預設值以及為 CSS 自定義屬性指定繼承行為等功能。

  • 允許你在樣式表中註冊自定義屬性,無需使用 JavaScript。

  • 建立已註冊的自定義屬性,類似於在 JavaScript 中使用等效引數呼叫registerProperty()

使用@property CSS @規則時的一些要點

  • 有效的@property規則意味著使用從規則序言中的序列化派生的屬性名稱來註冊自定義屬性。

  • @property規則必須同時包含syntaxinherits描述符。如果兩者任何一個缺失,則規則無效並被忽略。

  • 初始值描述符僅對於通用語法定義是可選的,否則是必需的。如果它缺失,則整個規則無效並被忽略。

  • @property規則中的未知描述符將被忽略並視為無效,但它們不會使整個@property規則無效。

語法

@property <custom-property-name> { <declaration-list> }      

CSS @property - 使用自定義屬性

以下示例演示了不使用 JavaScript 的@property

<html>
<head>
<style>
   @property --main-color {
      syntax: '<color>';
      inital-value: black;
      inherits: true;
   }
   .box {
      --main-color: red;
      background-color: var(--main-color);
      width: 200px;
      height: 200px;
      margin: 50px auto;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 24px;
      font-weight: bold;
      text-align: center;
   }
</style>
</head>
<body>
   <div class="box">
      <p>CSS At-Rules @property</p>
   </div>
</body>
</html>

CSS @property - 使用自定義屬性和 registerProperty()

以下示例演示了@propertyregisterProperty()的使用。

  • 在下面的示例中,CSS @property定義了一個名為--item-size的自定義屬性,並指定它接受和繼承百分比值,並以40%的初始值開始。

  • JavaScript中的window.CSS.registerProperty動態註冊一個名為--item-color的新自定義屬性,將其語法設定為<color>,指定它不繼承,併為其賦值初始值peachpuff

<html>
<head>
<style>
   @property --item-size {
      syntax: "<percentage>";
      inherits: true;
      initial-value: 40%;
   }
   /* set custom property values on parent */
   .container {
      display: flex;
      height: 100px;
      border: 3px dotted black;
      --item-size: 50%;
      --item-color: tomato;
      --item-border: 5px solid green;
   }
   /* use custom properties to set item size and background color */
   .item {
      width: var(--item-size);
      height: var(--item-size);
      border: var(--item-border);
      background-color: var(--item-color);
   }
   /* set custom property values on element itself */
   .second {
      --item-size: initial;
      --item-color: inherit;
   }
</style>
</head>
<body>
   <div class="container">
      <div class="item">First Item</div>
      <div class="item">Second Item</div>      
   </div>
<script>
   window.CSS.registerProperty({
   name: "--item-color",
   syntax: "<color>",
   inherits: false,
   initialValue: "peachpuff",
   });
</script>
</body>
</html>

描述符

描述符 解釋
syntax 解釋屬性允許的語法。
inherit 確定由@property定義的自定義屬性註冊是否預設繼承。
initial-value 定義屬性的初始值。
廣告
© . All rights reserved.