<p class="support">⚠️ Your browser does not support the CSS <code>:has()</code> selector so this demo won't work. Please try Safari TP 137.</p>
<figure>
<figcaption>CSS Pseudo-Class Specification</figcaption>
<img src="https://picsum.photos/1240/?random=11" alt="">
</figure>
<figure>
<div class="media">
<img src="https://picsum.photos/1240/?random=12" alt="">
</div>
<figcaption>CSS Pseudo-Class Specification</figcaption>
</figure>
<figure>
<img src="https://picsum.photos/1240/?random=13" alt="">
<figcaption>CSS Pseudo-Class Specification</figcaption>
</figure>
@import url("https://fonts.googleapis.com/css2?family=Exo:wght@600&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100vw;
min-height: 100vh;
font-family: "Exo", Arial, sans-serif;
background-color: #557;
display: grid;
gap: 1.25rem;
place-content: center;
font-size: clamp(1.5rem, 2vw + 1rem, 2.25rem);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr));
line-height: 1.5;
}
:where(img) {
max-width: 100%;
height: auto;
vertical-align: top;
}
figure {
background-color: #f4f4f4;
border-radius: 16px;
font-size: 1.25rem;
margin: 0;
overflow: hidden;
color: #000;
}
figcaption {
padding: 1rem 1.25rem;
margin: 0;
}
/* 匹配包含<figcaption>后代元素的<figure>元素 */
figure:has(figcaption) {
background-color: #3f51b5;
color: #fff;
}
/* 匹配包含<img>子元素的<figure>元素 */
figure:has(> img) {
background-color: #009688;
color: #fff;
}
/* 匹配包含<img>后代元素的<figure>元素 */
figure:has(img) {
background-color: #9c27b0;
color: #fff;
}
/* 匹配包含<img>后面有 <figcaption>元素的<figure>元素 */
figure:has(img + figcaption) {
background-color: #607d8b;
color: #fff;
}
.support {
color: #842029;
background-color: #f8d7da;
padding: 1rem 1rem;
border: 1px solid #f5c2c7;
border-radius: 0.25rem;
font-size: 1rem;
grid-column: 1 / -1;
}
@supports (selector(:has(*))) {
.support {
display: none;
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.