:focus-within

Keeping Parent Visible While Child in :focus

Say we have a <div></div>.

We only want this div to be visible when it's hovered, so:

div:hover { 
  opacity: 1; 
}

We need focus styles as well, for accessibility, so:

div:hover,
div:focus { 
  opacity: 1; 
}

But div's can't be focused on their own, so we'll need:

<div tabindex="0">
</div>

There is content in this div. Not just text, but links as well.

<div tabindex="0">
  <p>This little piggy went to market.</p>
  <a href="#market">Go to market</a>
</div>

This is where it gets tricky.

(more…)

:focus-within

The :focus-within pseudo selector in CSS is a bit unusual, although well-named and rather intuitive. It selects an element if that element contains any children that have :focus.

form:focus-within {
  background: lightyellow;
}

Which works like this...

<!-- this form will be selected -->
<form action="#">

  <!-- when this input is in focus -->
  <input type="text"/>

</form>

(more…)

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag