Détecter un élément vide avec :has() et :empty
HTML
index.html <ul><li></li><li></li></ul>
<ul>
<li>
<!-- not really empty cause of whitespace -->
</li>
<li>
<!-- not really empty cause of whitespace -->
</li>
</ul>
<ul>
<li>
élément 1
</li>
<li><!-- really empty --></li>
</ul>
<ul>
<li>élément 1</li>
<li>élément 2</li>
</ul>
CSS
style.css @layer demo {
ul:has(> *:empty) {
li {
display: none;
}
&::after {
content: 'Un des éléments de votre liste est vide';
color: red;
}
}
}
@layer demoStyles {
body {
flex-direction: row;
flex-wrap: wrap;
height: 100svh;
color: white;
}
ul {
list-style: none;
display: grid;
gap: 1rem;
min-width: 14rem;
padding: 1rem;
border: 1px solid #777;
border-radius: 10px;
background-image: linear-gradient(45deg, black, #222);
box-shadow: 0 0 25px 5px hsla(0deg 0% 0% / 100%);
}
li,
ul::after {
border: 1px solid;
padding: 0.5rem 1rem;
border-radius: 5px;
background-image: linear-gradient(45deg, black, #222);
}
li {
color: green;
}
}