Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Recently I had a need to add a very simple bit of functionality to my blog that would show/hide some bbcode examples. I didn't want to use Bootstrap/jQuery for such a simple task so I looked around and found this simple CSS trick that does exactly what I need by using a checkbox to trigger showing/hiding a pre element, effectively simulating a Bootstrap Accordion.

Here's what it looks like...

Hidden:
divhide1.png


Visible:
divhide2.png


The CSS is very simple:
 CSS
input[type=checkbox]:checked + pre {
display: none;
}


To explain this - the :checked pseudo-class applies when the checkbox is selected/checked and the '+ pre' part is an adjacent selector for the pre element. Together this means 'when there is a checked checkbox next to a pre element'.

Now the HTML is like this...
 HTML
<input type="checkbox" checked> Hide Content</input>
<pre>
Your content to show/hide
</pre>


As long as the pre element is immediately after the checkbox this will work. Apply your own styling to make it look how you want, no JavaScript/jQuery required!

You can also replace the pre element with just about anything else, as long as the style is updated and you use the new element after the checkbox.



-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.