Reputation: 3517
I need a css3 selector to target an element when the :target equals the id of the element (easy) or when the :target
is empty (impossible?). It’s hard to explain, so let me give you a simple example.
div {
background: blue;
}
div:target, div:no-target {
background: red;
}
But of course the :no-target
pseudo class doesn’t exist ;). Is there a way around this without using Javascript? Thanks in advance!
Upvotes: 13
Views: 10131
Reputation: 1669
With the :has selector gaining adoption, the following works (add a "default" class to the section to display when no target)
section {
display:none
}
section:target, :root:not(:has(:target)) section.default {
display: block
}
As of Nov 2023 this works in Safari/Chrome, not yet Firefox but presumably won't be long
Upvotes: 0
Reputation: 600
Sigh. I feel like I'm resurrecting a dead topic, but it needs a real answer.
It's possible to do this with CSS alone, just by using :last-child
and a general sibling combinator, in the form of :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 applies in the following steps:
.page:target ~ .page:last-child
)Edit: Apparently this is very similar to the accepted answer in an older, previously mentioned, related post.
Upvotes: 35
Reputation: 3014
There is a great answer for this over at default-target-with-css
It revolves around this trick that seems to have problems in iOS. It's been fixed in Safari, so maybe it'll be in iOS 5?
Upvotes: 1
Reputation: 707416
All I can think of is that you have some javascript that checks to see 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 the noHash class available in your CSS rules.
if (window.location.hash.length <= 1) {
document.body.className += " noHash";
}
Then, your CSS could be like this:
div {
background: blue;
}
div:target, body.noHash div {
background: red;
}
If there's any circumstance where a user might add a hash value after the fact, then you may have to watch for that to make sure the noHash class gets removed appropriately.
Note: you don't have to add the class name to the body tag. You can add it to any parent object that covers all the objects you wish to affect.
Upvotes: 1