2

Is there any way (using CSS only) to add padding to an element if it is NOT the only VISIBLE child?

So far I have it using :NOT and :only-child selectors:

div span:not(:only-child) {
    padding-right:5px;
}

However unfortunately if another child exists BUT it is hidden it is considered not to be the only child and the padding gets applied.

Demo here: http://jsfiddle.net/3Qr7v/

Hope that makes sense.

Thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Martin
  • 795
  • 1
  • 12
  • 31
  • 3
    I think `display:none` does not mean it's removed from the parent, so in fact the parent always has 2 children in both cases. – King King Apr 16 '14 at 13:55
  • 1
    you can do this using a script pure css will not do it. – ProllyGeek Apr 16 '14 at 13:55
  • Your first `span` is not the only child in either case anyway since there's a `br`; it is however `:only-of-type` where you would expect it to be `:only-child`. Just nitpicking of course, but then it explains why I use `:nth-child(2)` in my answer where you would otherwise have expected `:first-child` (I would even have used `:first-of-type` except [the version of jQuery that's used doesn't support it](http://stackoverflow.com/questions/11745274/what-css3-selectors-does-jquery-really-support-e-g-nth-last-child)). – BoltClock Apr 16 '14 at 14:35
  • Thanks guys, that is what I thought. Found an alternative easier solution - wish I saw it earlier...D'oh! – Martin Apr 17 '14 at 13:22

1 Answers1

1

There is no CSS selector for distinguishing visible elements from elements that are hidden or otherwise not apparent.

Since your demo uses jQuery, there is the :visible selector which makes it easy enough:

$("div span:nth-child(2):not(:has(+ span:visible))").css("padding-right", "5px");

If you can't use jQuery or your actual markup is much more complicated you'll have to find another way, either by modifying the markup or using a script, to determine when to apply that padding. Your situation can't be resolved using CSS only.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356