Menü schliessen
Created: December 20th 2024
Last updated: December 20th 2024
Categories: Common Web Development,  CSS,  IT Development
Author: Miljan Puzovic

Target other elements using :has()

Tags:  CSS,  guide
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

The :has() pseudo-class is implemented now in all modern browsers so it's safe to use it in production. This is one of the most powerful modern CSS features. It allows us to do things which were possible earlier only by using JavaScript.

In this example the goal when we hover one element to apply some style on all other elements. With :has() this is fairly easy.

For demonstration we can assume that we have this HTML structure:

<div class="container">
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div class="box">Box 3</div>
    <div class="box">Box 4</div>
</div>

and for demonstration purposes we're going to add some styles:

.container {
    display: flex;
    gap: 20px;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

.box {
    width: 100px;
    height: 100px;
    background-color: #3498db;
    transition: opacity 0.3s ease;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-family: Arial, sans-serif;
    border-radius: 8px;
}

The most important part here is

.container:has(.box:hover) .box:not(:hover) {
    opacity: 0.5;
}

which basically means: "When the container has any box being hovered, select all boxes that are not being hovered."

You can see the DEMO here.