:empty selector not working in css
Asked Answered
O

4

21

i used :empty selector in .error class. the problem is that even when there is no content inside the div with class of error, the error class is not removed completely. when i tested in firebug, i found that the div still has some whitespace and when i remove that extra spaces, the div then disappears.

.error{ border:solid 1px #ff0000; color:#ff0000;}
.error:empty{ display:none;}

the div shows like this on debugging:

<div class="error">     </div>

that extra spaces you see is the problem. Is there any way i can show &nbsp; in css to display:none ? pls help.

Outfight answered 19/8, 2013 at 12:20 Comment(1)
Do you have any control over the output?Britisher
H
25

it is because <div class="error"> </div>(demo) is not empty, it has a text node as the child.

:empty

The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered. Comments or processing instructions do not affect whether an element is considered empty or not.

Try

<div class="error"></div>

Demo: Fiddle

Hollyanne answered 19/8, 2013 at 12:25 Comment(1)
I think that's precisely the problem though, I don't think the OP has control over the HTML output.Britisher
E
5

If you only have specific elements as children you could try this:

.error:not(:has(yourChildElements)) {
   display: none;
}
Epicene answered 17/11, 2022 at 16:58 Comment(0)
A
2

The :empty pseudo-class doesn't select elements, containing elements or text (and white space is text).

However, there is now the experimental :blank pseudo-class which selects elements, containing nothing or just white space, and .error:blank would select that <div> element. You should avoid using experimental features in your production code, though.

Athwart answered 5/1, 2019 at 21:10 Comment(3)
People should keep in mind that :blank is not supported on most browsers: caniuse.com/#feat=mdn-css_selectors_blankDuroc
@JulienLeCoupanec I believe he mentionned that :blank is experimental, so I don't see any reason to downvote him?Elexa
@AdnaneAr yes. It was to add the link caniuse that I submitted this comment. I did not downvoted him.Duroc
A
1

Here's an alternative:

.error:not(:has(*)) {
    display: none;
}

This will select a class if it has nothing inside.

Augite answered 29/5, 2024 at 15:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.