CSS selector when: target empty

I need a css3 selector to target an element when: target is the element id (simple) or when :target empty (impossible?). It is difficult to explain, so let me give you a simple example.

 div { background: blue; } div:target, div:no-target { background: red; } 

But, of course, the pseudo-class :no-target does not exist;). Is there any way around this without using Javascript ? Thanks in advance!

+8
source share
5 answers

Sigh. It seems to me that I am resurrecting a dead topic, but this requires a real answer.

This can only be done using CSS, simply using :last-child and a common sibling combinator , in the form :target ~ :last-child :

 .pages > .page:target ~ .page:last-child, .pages > .page { display: none; } /* :last-child works, but .page:last-child will not */ .pages > :last-child, .pages > .page:target { display: block; } 

The rules apply in the following steps:

  1. hide all pages
  2. show both the landing page and the last page
  3. if the page is targeted, hide the last page ( .page:target ~ .page:last-child )

(live example)

Edit: Apparently, this is very similar to the accepted answer in the earlier post mentioned earlier .

+27
source

There is a great answer for this with default-target-with-css

It revolves around this trick , which seems to have problems with iOS. It has been fixed in Safari, so maybe it will be in iOS 5?

+2
source

All I can imagine is that you have javascript that checks if the hash is empty. If so, it adds a class to the body tag called noHash. Then you can use the fact that there is a noHash class in your CSS rules.

 if (window.location.hash.length <= 1) { document.body.className += " noHash"; } 

Then your CSS might look like this:

 div { background: blue; } div:target, body.noHash div { background: red; } 

If there are any circumstances in which the user can add a hash value after the fact, then you may need to monitor this to make sure that the noHash class is deleted remotely.

Note: you do not need to add the class name to the body tag. You can add it to any parent object that covers all the objects that you want to affect.

+1
source

Why don't you use div:not(:target) or div:target:empty ?

+1
source

You can use the :not(:target) selector.

-one
source

All Articles