Home >Web Front-end >CSS Tutorial >How Can I Display and Hide Elements on Demand Using Only CSS?
Display and Hide Elements on Demand with CSS
Navigating web content should be an effortless experience, regardless of browser settings or device limitations. In cases where JavaScript is unavailable, ensuring accessibility is crucial.
Consider a scenario with a menu and multiple hidden divs. The user's selection should trigger the appearance of specific divs. While JavaScript offers an ideal solution, it ceases to function when disabled.
CSS to the Rescue
To overcome this challenge, CSS comes to our aid. The "checkbox hack" harnesses the power of checkboxes and the versatile :checked pseudo selector.
How it Works
Initially, a checkbox and multiple divs are created. The checkbox is assigned three styles:
Implementation
In the HTML, create checkbox elements and corresponding label elements with each label associated with a unique div.
<input type="checkbox">
In the CSS, define the styles for the checkbox and labels:
/* Hide checkbox visually */ input[type="checkbox"] { display: none; } /* Use label for checkbox to provide visual accessibility */ label { display: inline-block; cursor: pointer; } /* Hide divs initially */ div { display: none; } /* Show div when associated checkbox is checked */ input[type="checkbox"]:checked ~ div { display: inline-block; }
Conclusion
With this CSS-based solution, divs can be seamlessly displayed or hidden on click, even with JavaScript disabled, ensuring a universally accessible user experience.
The above is the detailed content of How Can I Display and Hide Elements on Demand Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!