I have a url where I used target, example: www.hello.com/#targeturl
I want to use that to hide an element, and also show a different element that’s hidden. Is there a way to go about doing this?
The way I tried doing it was by using the below to show two "display: none" elements
<div id="targeturl" class="classy">
<div id="targeturl" class="classier">
and then used the CSS:
#targeturl.classy:target {
display: block!important;
}
#targeturl.classier:target {
display: block!important;
}
But of course this doesn’t work, is there a way to make this happen?
2
Answers
You can do that without JS using the
<label>
–<input type="checkbox">
trick:Note that this will scroll to the checkbox instead of the two
<div>
s. Setting a differentid
for it (or hide it usingdisplay: none
/visibility: hidden
) will effectively remove this behaviour altogether.Solution using
:target
As said in the comments, ID should be unique, but we can still use unique ID to show/hide elements with CSS.
As long as the ID is attached in an element that is at least the lowest common ancestor and the oldest of the elements you want to hide (classy, classiest, classiest), we can use CSS sibling combinator (~) and do this:
If you’re fine with changing the HTML structure, it’s also better to attach the ID to the parent of the elements you want to hide: