CSS sibling selector when hover

CSS Sibling Selector for Hover Effects

The sibling selector in CSS allows you to apply styles to an element when a sibling element is hovered. For instance, if you want to change the style of a paragraph when its preceding element is hovered, you can use the ~ (general sibling combinator).

Step 1: HTML

Create an HTML file and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS sibling selector when hover</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
      <a href="#" class="hover"></a>
      <a href="#" class="hover"></a>
      <a href="#" class="hover"></a>
    </div>
</body>
</html>

Step 2: CSS

Create a styles.css file and add the following code:

body {
	 justify-content: center;
	 align-items: center; background: #000;
	 min-height: 100vh; display: flex;
}
.container {
	 padding: 0 2rem; display: flex; width: 30%;
}
.hover {
	 text-decoration: none;
	 padding: 4rem 2rem; text-align: center;
	 font-weight: 700; transition: 0.5s;
	 flex: 1 1 25%; color: #000;
}
.hover { background: #fad29c; }
.hover::before { content: 'Before'; }
.hover:focus, .hover:hover { 
	background: #fff; color: blue;
}
.hover:focus::before, .hover:hover::before {
	 content: 'Hovered';
}
.hover:focus ~ .hover, .hover:hover ~ .hover {
	 background: #6ef1cd;
}
.hover:focus ~ .hover::before, .hover:hover ~ .hover::before {
	 content: 'After';
}
.container:not(:focus-within):not(:hover) .hover {
	 background: #f7ffb5;
}
.container:not(:focus-within):not(:hover) .hover::before {
	 content: 'Hover Me';
}

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *