Home  >  Article  >  Web Front-end  >  How to Hide/Show Content with CSS Only and Prevent Accidental Hiding?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 01:50:29586browse

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>

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>

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!

Statement:
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