Usually every time we want to toggle content on a website on click we use javascript. In this article, we are going to explore a different way of doing this by just using CSS capabilities.
The power behind :target selector
Not many people know this but there is a fantastic pseudo-class that allows us to apply styles to elements when a specific hash link is present or not in an URL, the name of this pseudo-element is :target and it is the protagonist of this short article.
Straight to the point, let's toggle stuff
Based on the explanation above, you may now imagine what I am about to do, so let's do it:
First, let's create a base HTML structure
<div><p>This is some expandable content.</p><pid="hashLink">
I have expanded like a Pufferfish.
<ahref="#">Please collapse this poor fish.</a></p></div><ahref="#hashLink">Expand</a>
We are creating one anchor to add a hash #hashLink to the URL (Expands the content).
We are creating a second anchor inside of the second paragraph to remove that anchor and leave it empty (Collapses the content).
The content we want to toggle is contained within a paragraph that has an id equal to the hash we are going to be adding to the URL.
We are adding a display: none; to the element with id hashLink so that it is hidden by default.
We are adding a display: block; to the #hashLink:target selector, this is what makes the magic happen, when the hash is present in the URL this style gets applied, creating the effect of toggling on click.
There is no really much more to explain, as you see it is straightforward, if you want to see a live example check the codepen below.
This selector is powerful, be creative and feel free to post cool things you decide to do with it.
Big O notation allows us to evaluate the performance of algorithms so that we can determine their efficiency and make decisions based on this determinations, let's try to understand how this notation works and how we can apply it in our lives as software developers.Read more
Linked Lists are a fundamental data structure in the world of software development, in this article we will explore its implementation and its applications in today's worldRead more