Trying out this method may or may not yield the desired results for you, but here is how I accomplish it using solely CSS. It's important to note that this approach relies on the focus-within
property, which unfortunately is not supported by IE or Edge browsers.
.parent {
transition: background-color;
}
.parent:active:not(:focus-within) {
background-color: red;
transition-delay: 1ms; // Introducing a delay to allow child element to focus
}
In essence, what happens here is that both the parent and the clicked child elements receive an active state. However, the key difference lies in the fact that the focus is applied to the child element only in the subsequent cycle. To prevent any conflicting animations during this transitional period, a minimal delay of 1ms is added. In the following cycle, the element becomes active with the focus shifted to the child, thereby bypassing the transition in the parent element. A similar approach can be taken with animation delay: 1ms
.
An alternative technique involves assigning a tabindex=-1
attribute to the item:
.parent {
transition: background-color;
}
.parent:active:focus {
background-color: red;
}
The downside to this method is its potential impact on keyboard navigation behavior and reliance on specific HTML attributes. For cases where keyboard navigation is required, consider using tabindex=0
or any value other than -1
, without involving JavaScript.
While there are polyfills available for focus-within
to cater to IE/Edge compatibility, implementing those would go beyond the realm of "CSS Only".
However, combining both techniques leads to the following solution:
.parent {
transition: background-color;
}
.parent[tabindex]:active:focus {
background-color: red;
}
.parent:active:not(:focus):not(:focus-within) {
background-color: red;
transition-delay: 1ms;
}
This combined approach is functional across IE11, Edge, and Chrome.
http://jsfiddle.net/s0at4w4b/42/