Home > Web Front-end > CSS Tutorial > How to Create a Collapsible Content List with Pure CSS: How do you prevent content from hiding when you click anywhere on the page?

How to Create a Collapsible Content List with Pure CSS: How do you prevent content from hiding when you click anywhere on the page?

DDD
Release: 2024-11-01 18:01:30
Original
339 people have browsed it

How to Create a Collapsible Content List with Pure CSS: How do you prevent content from hiding when you click anywhere on the page?

Hide and Show Content Seamlessly with CSS

To achieve a collapsible content list with pure CSS, we encounter a challenge: content can be hidden by simply clicking anywhere on the page. This deviates from the desired behavior of hiding content only when the "Hide" link is clicked.

The CSS Solution

The solution lies in leveraging the :focus and ~ selectors. The revised CSS code:

<code class="css">body {
  display: block;
}
.span3:focus ~ .alert {
  display: none;
}
.span2:focus ~ .alert {
  display: block;
}
.alert {
  display: none;
}</code>
Copy after login

The HTML Markup

<code class="html"><span class="span3">Hide Me</span>
<span class="span2">Show Me</span>
<p class="alert">Some alarming information here</p></code>
Copy after login

Understanding the Solution

  1. Focus State: The :focus selector targets the element that has received focus (e.g., when clicked).
  2. Sibling Selector (~): The ~ selector matches an element that is a sibling of the selected element.
  3. Conditional Display: The CSS rules set the display property of the .alert element based on the focus state of the .span3 and .span2 elements.

When the "Hide Me" link (.span3) receives focus, its sibling, the .alert element becomes hidden. Conversely, when the "Show Me" link (.span2) receives focus, its sibling, the .alert element becomes visible. This ensures that the content is hidden or shown only when the corresponding link is clicked, as intended.

The above is the detailed content of How to Create a Collapsible Content List with Pure CSS: How do you prevent content from hiding when you click anywhere on the page?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template