Ocultar Mostrar contenido-lista con solo CSS, no se utiliza javascript


He estado buscando un buen truco para hacer un contenido Hide/Show o una lista con solo CSS y sin javascript. He logrado hacer esta acción:

<!DOCTYPE html>
<head>

   <style>
      #cont {display: none; }
      .show:focus + .hide {display: inline; }
      .show:focus + .hide + #cont {display: block;}
   </style>

</head>
<body>

   <div>
        <a href="#show"class="show">[Show]</a>
        <a href="#hide"class="hide">/ [Hide]</a>
        <div id="cont">Content</div>
   </div>

</body>
</html>

Demo aquí: http://jsfiddle.net/6W7XD / Y está funcionando, pero no como debería. Aquí está el problema: Cuando se muestra el contenido, puede ocultarlo haciendo clic en "en cualquier lugar de la página". Cómo desactivar eso? ¿cómo ocultar el contenido "solo" haciendo clic en ocultar? Gracias de antemano!

Author: Frederic Kizar, 2013-07-18

10 answers

No usaría casillas de verificación, usaría el código que ya tiene

DEMO http://jsfiddle.net/6W7XD/1 /

CSS

body {
  display: block;
}
.span3:focus ~ .alert {
  display: none;
}
.span2:focus ~ .alert {
  display: block;
}
.alert{display:none;}

HTML

<span class="span3">Hide Me</span>
<span class="span2">Show Me</span>
<p class="alert" >Some alarming information here</p>

De esta manera el texto solo se oculta al hacer clic en el elemento ocultar

 25
Author: Kevin Lynch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-18 21:31:32

Esto va a volar tu mente: Botones de radio ocultos.

HTML:

<label for="show">
    <span>[Show]</span>
</label>
<input type=radio id="show" name="group">
<label for="hide">
    <span>[Hide]</span> 
</label>    
<input type=radio id="hide" name="group">
<span id="content">Content</span>

Y CSS:

input#show, input#hide {
    display:none;
}

span#content {
    display:none;
}
input#show:checked ~ span#content {
  display:block;
}

input#hide:checked ~ span#content {
    display:none;
}
 13
Author: Pat Lillis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-18 20:39:32

Hay 3 ejemplos rápidos con CSS puro y sin javascript donde el contenido aparece "al hacer clic", con un" clic mantenido "y un tercero" onhover " (todo solo probado en Chrome). Lo siento por el hasta de este post, pero esta pregunta son el primer resultado seo y tal vez mi contribución puede ayudar a principiante como yo

Creo que (no probado) pero la ventaja de argumento "contenido" que se puede añadir gran icono como de Fuente Impresionante (su \f-Code) o un icono hexadecimal en su lugar del texto "Ocultar" y "Mostrar" para internacionalizar el truco.

Enlace de ejemplo http://jsfiddle.net/MonkeyTime/h3E9p/2 /

<style>
label { position: absolute; top:0; left:0}

input#show, input#hide {
    display:none;
}

span#content {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}

input#show:checked ~ .show:before {
    content: ""
}
input#show:checked ~ .hide:before {
    content: "Hide"
}

input#hide:checked ~ .hide:before {
    content: ""
}
input#hide:checked ~ .show:before {
    content: "Show"
}
input#show:checked ~ span#content {
    opacity: 1;
    font-size: 100%;
    height: auto;
}
input#hide:checked ~ span#content {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}
</style>
<input type="radio" id="show" name="group">   
<input type="radio" id="hide" name="group" checked>
<label for="hide" class="hide"></label>
<label for="show" class="show"></label>
<span id="content">Lorem iupsum dolor si amet</span>


<style>
#show1 { position: absolute; top:20px; left:0}
#content1 {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}
#show1:before {
    content: "Show"
}
#show1:active.show1:before {
    content: "Hide"
}
#show1:active ~ span#content1 {
    opacity: 1;
    font-size: 100%;
    height: auto;
}
</style>

<div id="show1" class="show1"></div>
<span id="content1">Ipsum Lorem</span>


<style>
#show2 { position: absolute; top:40px; left:0}
#content2 {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}
#show2:before {
    content: "Show"
}
#show2:hover.show2:before {
    content: "Hide"
}
#show2:hover ~ span#content2 {
    opacity: 1;
    font-size: 100%;
    height: auto;
}

/* extra */
#content, #content1, #content2 {
    float: left;
    margin: 100px auto;
}
</style>

<div id="show2" class="show2"></div>
<span id="content2">Lorem Ipsum</span>
 8
Author: MonkeyTime,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-06 12:26:58

Esto es lo que he usado recientemente.

CSS

div#tabs p{display:none;}

div#tabs p.tab1:target {display:block;}
div#tabs p.tab2:target {display:block;}
div#tabs p.tab3:target {display:block;}

HTML

<div id='tabs'>
  <h2 class="nav-tab-wrapper">
    <a href="#tab1" class="nav-tab tab1">Pages</a>
    <a href="#tab2" class="nav-tab nav-tab-active tab2">Email</a>
    <a href="#tab3" class="nav-tab tab3">Support</a>
  </h2>

  <p id='tab1' class='tab1'>Awesome tab1 stuff</p>
  <p id='tab2' class='tab2'>Tab2 stuff</p>
  <p id='tab3' class='tab3'>Tab3 stuff</p>

</div>

Https://jsfiddle.net/hoq0djwc/1 /

Espero que ayude en alguna parte.

 4
Author: William,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-17 04:19:25

Primero, gracias a William.

Segundo - necesitaba una versión dinámica. Y funciona!

Un ejemplo:

CSS:

p[id^="detailView-"]
{
    display: none;
}

p[id^="detailView-"]:target
{
    display: block;
}

HTML:

<a href="#detailView-1">Show View1</a>
<p id="detailView-1">View1</p>

<a href="#detailView-2">Show View2</a>
<p id="detailView-2">View2</p>
 4
Author: lsblsb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 13:20:25

Usé una casilla de verificación oculta para ver persistentemente algún mensaje. La casilla de verificación podría estar oculta (display: none) o no. Este es un pequeño código que podría escribir.

Puedes ver y probar la demo en JSFiddle

HTML:

<input type=checkbox id="show">
<label for="show">Help?</label>
<span id="content">Do you need some help?</span>

CSS:

#show,#content{display:none;}
#show:checked~#content{display:block;}

Ejecutar fragmento de código:

#show,#content{display:none;}
#show:checked~#content{display:block;}
<input id="show" type=checkbox>
<label for="show">Click for Help</label>
<span  id="content">Do you need some help?</span>

Http://jsfiddle.net/9s8scbL7 /

 3
Author: lynx_74,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-01 02:01:32

Tengo otra solución simple:

HTML:

<a href="#alert" class="span3" tabindex="0">Hide Me</a>
<a href="#" class="span2" tabindex="0">Show Me</a>
<p id="alert" class="alert" >Some alarming information here</p>

CSS:

body { display: block; }
p.alert:target { display: none; }

Fuente: http://css-tricks.com/off-canvas-menu-with-css-target/

 1
Author: Miguel Garrido,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-12 04:04:23

Una solución muy fácil de cssportal.com

Si se presiona [mostrar], el texto [mostrar] estará oculto y al revés.

Este ejemplo no funciona en Chrome, no sé por qué...

.show {
	display: none;
}
.hide:focus + .show {
	display: inline;
}
.hide:focus {
	display: none;
}
.hide:focus ~ #list { display:none; }
@media print {
.hide, .show {
	display: none;
}
}
<div><a class="hide" href="#">[hide]</a> <a class="show" href="#">[show]</a>
<ol id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ol>
</div>
 1
Author: user2422690,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-31 13:31:10

Sé que es un post antiguo, pero qué pasa con esta solución ( He hecho un JSFiddle para ilustrarlo)... Solución que utiliza los pseudo elementos :after de <span> para mostrar/ocultar el enlace del interruptor <span> (además del mensaje .alert debe mostrar/ocultar). Cuando el pseudo elemento pierde su enfoque, el mensaje se oculta.

La situación inicial es un mensaje oculto que aparece cuando el <span> con el :after content : "Show Me"; está enfocado. Cuando este <span> está enfocado, es :after content se vuelve vacío mientras que el :after content del segundo <span> (que inicialmente estaba vacío) se convierte en "Hide Me". Entonces, cuando haces clic en este segundo <span> el primero pierde su enfoque y la situación vuelve a su estado inicial.

Comencé con la solución ofrecida por @ Vector Mantuve la situación del DOM presentada ky @Frederic Kizar

HTML:

<span class="span3" tabindex="0"></span>
<span class="span2" tabindex="0"></span>
<p class="alert" >Some message to show here</p>

CSS:

body {
    display: inline-block;
}
.span3 ~ .span2:after{
    content:"";
}
.span3:focus ~ .alert  {
    display:block;
}
.span3:focus ~ .span2:after  {
    content:"Hide Me";
}
.span3:after  {
    content: "Show Me";
}
.span3:focus:after  {
    content: "";
}
.alert  {
    display:none;
}
 1
Author: Diepen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-18 01:56:33

La respuesta a continuación incluye cambiar el texto por "mostrar/ocultar", y utiliza una sola casilla de verificación, dos etiquetas, un total de cuatro líneas de html y cinco líneas de css. También comienza con el contenido oculto.

Pruébalo en JSFiddle

HTML

<input id="display-toggle" type=checkbox>
<label id="display-button" for="display-toggle"><span>Display Content</span></label>
<label id="hide-button" for="display-toggle"><span>Hide Content</span></label>    
<div id="hidden-content"><br />Hidden Content</div>

CSS

label {
  background-color: #ccc;
  color: brown;
  padding: 15px;
  text-decoration: none;
  font-size: 16px;
  border: 2px solid brown;
  border-radius: 5px;
  display: block;
  width: 200px;
  text-align: center;
}

input,
label#hide-button,
#hidden-content {
  display: none;
}

input#display-toggle:checked ~ label#display-button {
  display: none;
}

input#display-toggle:checked ~ label#hide-button {
  display: block;
  background-color: #aaa;
  color: #333
}

input#display-toggle:checked ~ #hidden-content {
  display: block;
} 
 0
Author: jeffmcneill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 14:08:00