(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.data-privacy-src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-1596564-1', 'auto'); ga('send', 'pageview');
Home » NewsBlog » Keeping Parent Visible While Child in :focus

Keeping Parent Visible While Child in :focus

Say we have a

.

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:

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

This little piggy went to market.

Go to market

This is where it gets tricky.

As soon as focus moves from the div to the anchor link inside it, the div is no longer in focus, which leads to this weird and potentially confusing situation:

In this example, :hover reveals the div, including the link inside. Focusing the div also works, but as soon as you tab to move focus to the link, everything disappears. The link inside can recieve focus, but it’s visually hidden because the div parent is visually hidden.

One solution here is to ensure that the div remains visible when anything inside of it is focused. New CSS has our back here:

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

GIF working

But browser support isn’t great for :focus-within. If it was perfect, this is all we would need. In fact we wouldn’t even need :focus because :focus-within handles that also.

But until then, we might need JavaScript to help. How you actually approach this depends, but the idea would be something like…

  1. When a element comes into focus…
  2. If the parent of that element is also focusable, make sure it is visible
  3. When the link leaves focus…
  4. Whatever you did to make sure the parent visible is reversed

There is a lot to consider here, like which elements you actually want to watch, how to make them visible, and how far up the tree you want to go.

Something like this is a very basic approach:

var link = document.querySelector(".deal-with-focus-with-javascript");

link.addEventListener("focus", function() {
  link.parentElement.classList.add("focus");
});
link.addEventListener("blur", function() {
  link.parentElement.classList.remove("focus");
});

See the Pen :focus-within helpful a11y thing by Chris Coyier (@chriscoyier) on CodePen.


Keeping Parent Visible While Child in :focus is a post from CSS-Tricks

CSS Tricks Go to Source
Author: Chris Coyier

Powered by WPeMatico

2017-12-13T03:01:50+00:00December 13th, 2017|Categories: News, Tutorials|Tags: |
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Ok