容器查询卡片

此演示版使用容器查询来创建固有的自适应卡片。卡片布局从较窄的单列布局变为较宽的双列布局。

如需创建容器,请先在父级上设置容器:

/* Set containment on parent */ .container {   container-name: myContainer;   container-type: inline-size;   /* You can also use the shorthand property `container: myContainer / inline-size`. } 

您可以设置一些基本样式:

.desc {   display: none; }  .card {   text-align: center;   padding: 0.5rem; } 

然后根据该父容器的内嵌宽度更新这些基本样式:

/* 2-column grid layout at >=350px */ @container (min-width: 350px) {   .card {     display: grid;     grid-template-columns: 40% 1fr;     align-items: center;     gap: 1rem;     text-align: left;   } }  /* Display description at >=500px */ @container (min-width: 500px) {   .desc {     display: block;   } } 

这意味着,如果您在界面的不同部分添加了完全相同的组件,该组件便可使用自己的逻辑来调整其大小,使其最适合自己的容器。与仅使用全局视口时相比,您可以更好地控制卡片布局。下面的示例将容器查询卡片放置在列宽不同的网格中:

在 Codepen 上探索此演示版应用

HTML

<div class="container">   <div class="card">     <div class="visual"></div>     <div>       <div class="meta">         <h1>Card Title Here</h1>         <h2 class="time">Subtitle</h2>       </div>         <p class="desc">Here is some descriptive text to support the main idea of the card. It will be hidden when there is less inline space.</p>       <button>I'm a button</button>     </div>   </div> </div>

CSS

         /* Set containment on parent */ .container {   container: inline-size;   width: 100%;   max-width: 750px;   margin: 0 auto; }  /* Base Styles */ .visual {   aspect-ratio: 1 / 1; }  .desc {   display: none; }  .card {   text-align: center;   padding: 0.5rem; }  /* Responsive styles */  /* 2-column grid layout at >=350px */ @container (min-width: 350px) {   .card {     display: grid;     grid-template-columns: 40% 1fr;     align-items: center;     gap: 1rem;     text-align: left;   } }  /* Display description at >=500px */ @container (min-width: 500px) {   .desc {     display: block;   } }