The user experience can be greatly improved by dynamically controlling an element’s visibility in web design. With the help of CSS, you can make all div elements in HTML invisible, allowing you to make more aesthetically pleasing and interactive web pages. By learning this straightforward but effective technique, you’ll be able to more easily manage content visibility, optimize page design, and improve user engagement.
Guide on how to hide div elements
Here I am using internal CSS to do the styling of the elements.
First I am creating a div element as follows inside which I will store 2 more div elements which I will be hiding:
<div class="container">
Once I create the div element inside the body tag I create 2 more div elements. Then I am going to make a style tag inside the head tag where all the CSS declarations will fall. The declarations will be used to give the web page background colors, font styles, size, alignment, etc.
There are 2 main declarations which will help in hiding the div elements, they are:
.hide-checkbox { display: none; }
The selector targets all the HTML elements with the class as ‘hide-checkbox’, the declaration ‘display’ hides the elements by setting their display property to ‘none’.
.hide-checkbox:checked + .center { display: none; }
This complex selector targets a ‘.center’ element preceded by a ‘.hide-checkbox’ element in a checked state. The ‘: checked’ pseudo-class applies to checked input elements. The adjacent sibling combinator ‘+’ selects the next sibling with the ‘.center’ class. The ‘display: none;’ declaration hides the ‘.center’ element when the preceding ‘.hide-checkbox’ element is checked.
Coming back to the 2 div elements created inside each elements we write the following tags and attributes:
<input type="checkbox" id="div2" class="hide-checkbox"> <label for="div2" class="center">
The ‘<input>’ tag creates a checkbox input element, assigns a unique identifier to the checkbox and assigns the class ‘hide-checkbox’ to the checkbox. This class is used by the CSS to hide the checkbox and apply additional styles when the checkbox is checked.
The ‘<label>’ tag creates a label element that associates the it with the checkbox that has the id=”div2″, clicking on the label will toggle the checkbox and also assigns the class ‘center’ to the label.
The reason I have used the <label> tag and checkbox attribute is because by using a label with the ‘ for’ attribute linked to a checkbox, the user can click on the larger label area to toggle the checkbox, making it easier to interact with. After everything is set we get following results.
Results
When we run the program, we get below output on the webpage:
If we click on 1 of the div it hides
After we click on the 2nd div it also hides and we get the below result
This way we were able to hid all thew div elements in HTML using CSS only.