Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodeMyUI/de708e2510cc401e54c3e1e7b2776944 to your computer and use it in GitHub Desktop.
Save CodeMyUI/de708e2510cc401e54c3e1e7b2776944 to your computer and use it in GitHub Desktop.
CSS sibling selector with hover state

CSS sibling selector with hover state

Quick demo showing how you can target elements based on their position to a hovered element.

This is the 1-d version of how my directionally aware hover pen works.

A Pen by Giana on CodePen.

License.

<div class="container">
<a href="#" class="hover"></a>
<a href="#" class="hover"></a>
<a href="#" class="hover"></a>
<a href="#" class="hover"></a>
<a href="#" class="hover"></a>
</div>
.hover {
// Everything before the hovered element
// Since we can't select previous elements, we simply set it as the default and then overwrite subsequent elements
background: #fad29c;
&::before {
content: 'Before';
}
// The hovered element
&:focus,
&:hover {
background: #fff;
&::before {
content: 'Hovered';
}
}
// Everything after the hovered element
// ~ is the sibling selector https://developer.mozilla.org/en/docs/Web/CSS/General_sibling_selectors
&:focus ~ &,
&:hover ~ & {
background: #6ef1cd;
&::before {
content: 'After';
}
}
}
// If the container isn't hovered, set some default styles
// No IE/Edge support for :focus-within but you can restructure/remove this
// https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within
.container:not(:focus-within):not(:hover) {
.hover {
background: #f7ffb5;
&::before { content: 'Hover Me'; }
}
}
//== Pen styling, ignore
body {
justify-content: center;
align-items: center;
background: #fdfdff;
min-height: 100vh;
display: flex;
}
.container {
padding: 0 2rem;
display: flex;
width: 100%;
}
.hover {
text-decoration: none;
padding: 4rem 2rem;
text-align: center;
font-weight: 700;
transition: 0.5s;
flex: 1 1 25%;
color: #000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment