Another way that I think works and that I happen to need if the show/hide button is in another element which will make it impossible to use the ~
as in the example with :checked
, would use the :target
.
The :target
works based on the hash of the current page URL, an example of usage applied to parent element (can apply to the body, but will be a little more limited if you have more than one element)
a simple example would be:
- If the URL is something like
http://foo.bar/pagina
- If the URL is something like
http://foo.bar/pagina#box-1
will display the elements with class="mostrar"
within the <div id="box-1"></div>
, will hide the link with class="show-action"
and will display the link class="hide-action"
that are inside the <div id="box-1"></div>
- If the URL is something like
http://foo.bar/pagina#box-2
will display the elements with class="mostrar"
within the <div id="box-2"></div>
, will hide the link with class="show-action"
and will display the link class="hide-action"
that are inside the <div id="box-2"></div>
You can create more Divs with more Ids, it is important to remember that the Ids in HTML (this is HTML and not related to the CSS of my answer) can never repeat, ID = identity, ie each one has its own.
The "must URL" button in the example below is only to be able to see the URL inside the Stack Snippet, because it runs in an IFRAME
An example of testing:
/*
Oculta os elementos com a classe .mostrar
Oculta os elementos com a classe .hide-action
*/
#box-1 .mostrar,
#box-1 .hide-action,
#box-2 .mostrar,
#box-2 .hide-action {
display: none;
}
/*
conforme a HASH atual:
Mostra os elementos com a classe .mostrar
Mostra os elementos com a classe .hide-action
*/
#box-1:target .mostrar,
#box-1:target .hide-action,
#box-2:target .mostrar,
#box-2:target .hide-action {
display: block;
}
/*
conforme a HASH atual:
Oculta os elementos com a classe .action-action
*/
#box-1:target .show-action,
#box-2:target .show-action
{
display: none;
}
<div id="box-1">
<div class="foo">
<div class="bar">
<div class="mostrar">Olá Stack Overflow</div>
</div>
</div>
<div class="baz">
<a class="show-action" href="#box-1">Mostrar</a>
<a class="hide-action" href="#">Ocultar</a>
</div>
</div>
<div id="box-2">
<div class="foo">
<div class="bar">
<div class="mostrar">Olá Francis Vagner da Luz</div>
</div>
</div>
<div class="baz">
<a class="show-action" href="#box-2">Mostrar</a>
<a class="hide-action" href="#">Ocultar</a>
</div>
</div>
<button onclick="console.log(location.href);">Mostrar url</button>
Do you want to use only css? without javascript?
– N. Dias
Yes N. Days, you know how it’s done?
– Francis Vagner da Luz
Read on here https://stackoverflow.com/questions/13630229/can-i-have-an-onclick-effect-in-css
– N. Dias