3

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?

McKayla
  • 6,879
  • 5
  • 36
  • 48

2 Answers2

3

You can select elements that contain no other elements using the :empty selector, but what you need won't be available until CSS Selectors Level 4’s :has and :not(selector list) are both implemented in browsers. 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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    Obligatory jQuery propaganda `$('#hi:not(:has(.footer))')` – BoltClock Mar 07 '12 at 03:11
  • The answer was given in 2012. It is now 2022. A decade has come and gone. `:not()` has kind of arrived but `:has()` has not. jQuery propaganda has become even more irrelevant than it was back then. Has some new, CSS-only, way of achieving `.hi:has(.head)` emerged? – Sixtyfive Sep 23 '22 at 11:52
  • 1
    @Sixtyfive: `:has` is supported in current Chrome, and in Firefox behind a flag. Apart from that, no. – Ry- Sep 23 '22 at 19:27
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.

ScottS
  • 71,703
  • 13
  • 126
  • 146