Yes, it is possible. We can do it with just CSS.
Yes, you heard it right! Here’s how we can achieve the same output with only CSS.
How to Show /Hide HTML Elements with CSS
In this example, we are going to simply Show/Hide an unordered list (ul li). The first step is creating a button that we’ll name “Toggle.” Next, we’ll click on the button to show and hide the unordered list.
What You Need for the HTML
This is the most basic and simple HTML that we will work on. We have label, input type, checkbox, and ul li in our HTML. The checkbox should get checked/unchecked when someone clicks on the label content.
We use the attribute in the label, which has a “checkbox” ID as the input type, to achieve the same result. Here we have ID as “checkBtn” so we have added the value of the attribute as the same for “checkBtn.” We have also created a ul li and ul has an ID of “listing.”
What You Need for the CSS
These are the CSS styles that we’ll use. Initially, we have made the ul as “display none” by adding the style to id #listing as “display none.” We have also removed the input type of “checkbox” from our view by making “#checkBtn” as “display none.”
Now here’s the trick. When someone clicks on the label, the input type checkbox will be checked. This means that the pseudo-class will read as ”checked” on the #checkBtn, which is the input type checkbox tag. Whenever #checkBtn reads as “checked,” we can then use the ~ CSS selector to make the #listing, which is the ID for our ul, as a display block.
When you click on the toggle button (label) again, the pseudo class “checked” will detach and #listing will again revert to “display none.” We have to add the styling to the label to make it look like a button as well as add on-hover styling, which allows your mouse to actively hover over the button and show a reaction. This is how we can Show/Hide the HTML element using CSS only.
Note: You can also use the button and other tags available as your requirement, but it should be inside the label tag.
Here is the output demonstration in the picture below. When you click on the toggle button, the ul li list appears. When you click on the toggle button again, the ul li list disappears.
A Simple and Seamless Process
Using all the abilities of CSS can improve our site performance and speed. As long as we know the processes, anything is possible. To learn more about these technical processes, contact our experts today.