CSS rule to select an element which doesn't co

2020-05-07 10:06发布

问题:

I have a bunch of elements that look like..

<div id="hi">
    <div class="head">
    </div>
    <div class="footer">
    </div>
</div>

..except some of them don't have the footer element, only a head. I want to give elements without a footer a bottom border. I'm hoping for something like..

#hi:hasno(.footer) {
    border-bottom: 1px black dotted;
}

Is there a CSS selector I could use for this, or should I just use a JavaScript equivalent?

回答1:

You can select elements that contain no other elements using the :empty selector, but what you need won't be available until CSS4. So no, it can't be done in pure CSS. Now whether or not you should use a JavaScript equivalent depends on what you really want to achieve here. If it's a minor detail, feel free to add it with JavaScript if it's not too much of a problem. If it's a huge, essential feature, consider restructuring so you don't need this kind of selector.



回答2:

Depending on the situation with your background, you could put the border on #hi permanently, and then overlap that with your footer by giving the footer either margin-bottom: -1px or position: relative; bottom: -1px; and hiding the border when the footer is present.