Home >Web Front-end >CSS Tutorial >How to Prevent Unintended Content Hiding in CSS: A Solution for the \':focus\' Problem
Hide/Show Content-List with CSS: Resolving Unintended Behavior
In pursuit of a solution to hide and show content using only CSS, a developer encountered an issue: the content could be hidden by clicking anywhere on the page, rather than just by clicking the designated "hide" link.
The developer's initial code used the following CSS:
<code class="css">#cont {display: none; } .show:focus + .hide {display: inline; } .show:focus + .hide + #cont {display: block;}</code>
This code successfully hides the content when the "hide" link is clicked. However, it also enables hiding by clicking any part of the page, because the CSS rule targets the ":focus" pseudo-class.
To resolve this issue, we can use the following updated CSS:
<code class="css">body { display: block; } .span3:focus ~ .alert { display: none; } .span2:focus ~ .alert { display: block; } .alert{display:none;}</code>
In this updated code, we use the "~" combinator to target elements that are siblings of the focused element. This means that the "hide" element (~ .alert) is only hidden when the "show" element is in focus.
The HTML remains the same:
<code class="html"><span class="span3">Hide Me</span> <span class="span2">Show Me</span> <p class="alert" >Some alarming information here</p></code>
With this revised approach, the content is now only hidden when the "Hide Me" element is clicked, as the developer intended.
The above is the detailed content of How to Prevent Unintended Content Hiding in CSS: A Solution for the \':focus\' Problem. For more information, please follow other related articles on the PHP Chinese website!