Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element visible only if there are no siblings through CSS

Tags:

html

css

My current code looks something like this:

if list.isEmpty() {
    output("<div>No items</div>")
} else {
    for each item in list
        optput("<div>" + item + "</div>")
}

However, the whole "No items" logic belongs to the view and should be separated from the logic. Ideally, I'd like to have just

for each item in list
    optput("<div>" + item + "</div>")

And then have the HTML template look something like this:

<div id="container">
    <div style="visible only if no siblings">No items</div>
    <div>Item 1</div>
    <div>Item 2</div>
<div>

The problem is that I can't figure out how to do the "visible only if no siblings" part. Is there a way to achieve this reliably (works across all standard browsers) using CSS?

like image 276
aioobe Avatar asked Mar 19 '23 06:03

aioobe


1 Answers

Give the div you want to be visible only with no siblings a particular class:

<div id="container">
    <div class="vis-only-no-siblings">No items</div>
    <div>Item 1</div>
    <div>Item 2</div>
<div>

As long as the divs have no other siblings, you'll be able to use the :only-child pseudoselector, like so:

#container div.vis-only-no-siblings{
    display: none;
}

#container div.vis-only-no-siblings:only-child {
    display: block;
}
like image 149
kmoe Avatar answered Mar 26 '23 03:03

kmoe