CSS - 容器名稱



CSS 的container-name 屬性指定了一個可查詢容器名稱列表,這些名稱將由@container at-rule 在容器查詢中使用。容器查詢負責根據具有包含上下文的最近祖先或父級的尺寸來為元素應用樣式。

可能的值

container-name 屬性只能有一個值,如下所示

  • <container-name>:它是一個區分大小寫的字串,用於識別容器。在設定容器名稱時,需要滿足一些條件。

以下條件適用

  • 可以使用任何有效的<custom-ident>,但它不能等於default

  • 名稱值不能用引號括起來。

  • 開頭帶破折號表示使用者定義識別符號的識別符號是允許的,例如--container-name-sample

  • 允許用空格分隔的多個值。

應用於

所有 HTML 元素。

語法

container-name = none | <custom-ident>+  

CSS container-name - 基本示例

以下示例演示瞭如何使用container-name 屬性命名容器。

<html>
<head>
<style>
      .card {
         margin: 10px;
         border: 2px dotted;
         font-size: 1.5em;
         width: 500px;
      }
      .post {
         border: 2px solid red;
      }

      /* A container context based on inline size */
      .post {
         container-type: inline-size;
         container-name: sample;
      }

      /* Styles to be applied if the container's (here container is the div element, with class = .post) 
      min-width is 400px */
      
      @container sample (min-width: 400px) {
         p {
            visibility: hidden;
         }
      }
</style>
</head>
<body>
   <div class="post" >
      <div class="card">
         <h2>Card title</h2>
         <p>Card content Visible Now</p>
      </div>
   </div>   
</body>
</html>

以上示例中的容器查詢,當最小寬度為 400px 時,應用於.post 元素的內容。

調整視窗大小以檢視效果
廣告

© . All rights reserved.