How can I toggle multiple div visibility on click using only CSS?

Barbara Streisand
Release: 2024-11-24 11:37:10
Original
820 people have browsed it

How can I toggle multiple div visibility on click using only CSS?

Controlling Div Visibility on Click Using CSS

Problem:

A user wishes to toggle the visibility of multiple divs on click using solely CSS, allowing accessibility without JavaScript.

Solution:

Employ the "checkbox hack":

  1. Create a hidden checkbox: Define a element and set its display to none using CSS.
  2. Associate a click event with the checkbox: When the menu option is clicked, toggle the checkbox's checked attribute.
  3. Style divs based on checkbox state: Use the :checked pseudo selector in CSS to apply different styles to divs depending on whether the checkbox is checked or not. This affects their visibility, fading, or sliding behavior.

Code Example:

<input type="checkbox">
Copy after login
#myCheckbox:checked ~ #myDiv {
  display: block;
  animation: slide-in 0.5s ease-in-out;
}

@keyframes slide-in {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}
Copy after login

Benefits:

  • Accessibility: Works without JavaScript enabled.
  • Control: Adjust the CSS animations to customize the slide/fade behavior.
  • Simplicity: Requires minimal CSS code and no JavaScript.

The above is the detailed content of How can I toggle multiple div visibility on click using only CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template