12

I know how to collapse (display / hide) a div:

$('#nav').click(function() { $('#hello').toggleClass('hidden'); });
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="nav">NAV</div>
<div id="hello" class="hidden">Hello</div>

Is it possible to do this without Javascript / jQuery?

I've tried the main answer from this question, but it is not working, as detailed here.

Community
  • 1
  • 1
Basj
  • 41,386
  • 99
  • 383
  • 673

3 Answers3

42

Nobody has mentioned the 'details' element, which seems perfect for this job.

<details>
    <summary>Click to toggle</summary>
    <span>Oh, hello</span>
</details>
Matthew Spencer
  • 781
  • 1
  • 8
  • 11
26

You may use :checked selector.

#hidden {
  display: none;
  height: 100px;
  background: red;
}
:checked + #hidden {
  display: block;
}
<input type="checkbox" id="my_checkbox" style="display:none;">
<div id="hidden"></div>

<label for="my_checkbox">Show/hide</label>

Example fiddle

roberrrt-s
  • 7,914
  • 2
  • 46
  • 57
Denis Sheremet
  • 2,453
  • 2
  • 18
  • 34
  • 3
    This is really clever – caesay Dec 19 '16 at 10:51
  • This is basically the idea from the answer linked in OP's question – pawel Dec 19 '16 at 10:52
  • @DenisSheremet Thanks! PS: by the way do you know a nice CSS hamburger icon? I browsed many SO questions but didn't find a really good looking one... – Basj Dec 19 '16 at 10:54
  • Thanks a lot @DenisSheremet ! Here is my variation: https://jsfiddle.net/sgbs7ju9/4/ – Basj Dec 19 '16 at 14:16
  • How can I make the red box appear after the button instead of before? –  Aug 14 '18 at 12:13
  • 1
    @Kos just swap div and label and leave checkbox where it is. You'll also need to update css selector to `:checked ~ #hidden` or `:checked + * + #hidden`. – Denis Sheremet Aug 15 '18 at 11:25
-1

Well yes, it is, but it's not neat. It involves the :target selector, where you can apply styles to active elements / id's. If we wrap your nav content in a link, we can apply a hashtag which invokes the active rule in our CSS.

Downside, this jumps the page to the location unless prevented by... JavaScript.

a {
  color: #000;
  text-decoration: none;
}
  
#hidden {
  display: none;
}

#hidden:target {
  display: block;
}
<div id="nav"><a href="#hidden">NAV</a></div>
<div id="hidden">Hello</div>
roberrrt-s
  • 7,914
  • 2
  • 46
  • 57