Is it possible to style an element based on whether or not its next sibling is empty.
<ul class="menu">
<li class="label">Hide me when submenu is empty</li>
<ul class="submenu"></ul>
</ul>
Let's assume that I want to hide <LI class="label">
when <UL class="submenu">
is empty. Is this possible with CSS/Sass?
I've tried several variations of the example below, but haven't had any luck.
ul {
> li {
~ ul:empty {
display: none;
}
}
}
I'd prefer to stick with a CSS solution if possible.
The first, major problem your markup has is that it's invalid.
The only valid children of <ul>
elements are <li>
s. Therefore, in order to be valid, your inner <ul>
has to be inside the <li>
. It can't be an immediate child of another <ul>
.
But, even assuming a valid markup:
<ul class="menu">
<li class="label">Hide me when submenu is empty
<ul class="submenu"></ul>
</li>
</ul>
... what you're trying to do is not possible using CSS alone, because the CSS parser never goes backwards (or upwards, for that matter).
If you can't do it with CSS alone you can't do it with SCSS alone, because SCSS is CSS syntactic sugar.
Here's how a JavaScript solution would look like:
const uls = document.querySelectorAll('ul'); [...uls].forEach((ul) => { const emptyChildUls = ul.querySelectorAll('ul:empty'); [...emptyChildUls].forEach((emptyUl) => { emptyUl.parentElement.classList.add('hasEmptyList'); }) });
ul li.hasEmptyList { display: none; }
<ul> <li>Hide me when submenu is empty <ul></ul> </li> </ul>
Obviously, you can change the applied classname to whatever you want. I chose to add a class rather than perform direct changes to the DOM elements so that you could still retain a level of control via CSS.
The above script has to run after you finished adding <ul>
s to your page. If you add them after you ran the script, they won't have the class applied (you need to run the script again so they do).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.