How to Hide/Show Content with CSS Only and Prevent Accidental Hiding?

Patricia Arquette
Release: 2024-10-30 01:50:29
Original
600 people have browsed it

How to Hide/Show Content with CSS Only and Prevent Accidental Hiding?

Hide/Show Content-List with CSS Only

Problem:

How to hide/show content using only CSS without JavaScript, while ensuring that the content is only hidden by clicking the "Hide" button and not by clicking anywhere on the page.

Initial Solution:

The provided HTML and CSS code allows hiding and showing content, but the content can be hidden by clicking anywhere on the page.

Solution:

To resolve this issue, use the following modified CSS:

<code class="css">body {
  display: block;
}

.span3:focus ~ .alert {
  display: none;
}

.span2:focus ~ .alert {
  display: block;
}

.alert {
  display: none;
}</code>
Copy after login

And update the HTML structure accordingly:

<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

How It Works:

This solution uses the ~ (sibling) selector in CSS to target elements that are siblings of the focused element. When the "Hide Me" button is focused, it sets the adjacent .alert element to display: none;, hiding the content. Conversely, when the "Show Me" button is focused, it sets the adjacent .alert element to display: block;, showing the content.

The above is the detailed content of How to Hide/Show Content with CSS Only and Prevent Accidental Hiding?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!