Modifying the attribute of one element upon hovering over a different element positioned afterwards

I have two divs and I would like to change the color of the first one when hovering over the second one. I've seen solutions where the hovered element comes before the target element in CSS, but what if the hovered element comes after? Is there a way to achieve this without using JavaScript?

.box, .box-2 {
              display: block;
              height: 100px;
              width: 100px; 
              margin: 20px;
          }

          .box {
              background-color: red; 
          }

          .box-2 {
              background-color: blue;
          }

          .box-2:hover + .box {
              background-color: green;
          }
<body>
            <div class="wrapper"> 
                <div class="box"></div>
                <div class="box-2"></div>
            </div>
            </body>

Answer №1

An effective approach is to reverse the order visually while maintaining the original order in the DOM, allowing you to still utilize the + selector.

Below is a demonstration using flex:

.wrapper {
  display:flex;
  flex-direction:column;
}

.box, .box-2 {
  display: block;
  height: 100px;
  width: 100px;
  margin: 20px;
}

.box {
  background-color: red;
}

.box-2 {
  background-color: blue;
  order:2; /* this will make box-2 goes after */
}

.box-2:hover + .box {
  background-color: green;
}
<body>
<div class="wrapper"> 
  <div class="box-2"></div>
  <div class="box"></div>
</div>
</body>


Explore these related questions for further inspiration:

Is there a "previous sibling" CSS selector?

Previous adjacent sibling selector workaround?

Answer №2

Although Temani's approach is effective, I propose an alternative solution for a bidirectional functionality by utilizing the :not() selector. Keep in mind that this method may be somewhat unpredictable due to your margins.

To achieve styling for both hover states of an element, consider applying the following CSS rule within the context of a parent container with the class of .wrapper:

.wrapper:hover > .box:not(:hover) {
    background-color: green;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions on how to export an HTML table to Excel or PDF by including specific buttons using PHP or JavaScript

I created a table to display leave details of employees with sorting options from date to date. Now, I need to include buttons for exporting the data to Excel and PDF formats. Check out the code below: <form name="filter" method="POST"> <in ...

Tips for concealing a div upon reaching a specific scroll point, even with varying content sizes

Hey there! I am completely new to web programming and currently working on a landing page. The challenge I'm facing is that the content in the first column is dynamic, meaning it can vary in length. I'm looking for a way to hide my call-to-actio ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...

Using Python Selenium to extract data - a step-by-step guide

Here is the link you are looking for: I have successfully accessed this website using Selenium-Webdriver in Python. My next task is to extract the information about the battery type. https://i.sstatic.net/mSd6Y.jpg ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

Custom plugin shortcode HTML appearing within WordPress Edit Page interface

After developing my first WordPress plugin, I encountered a slight issue. Upon activating the plugin, the edit page screen became distorted. Attached is a screenshot for reference. https://i.sstatic.net/wB5aj.png Upon further inspection, it seems that th ...

Collapsed navbar icon unresponsive exclusively on extremely compact displays

I designed my own responsive navbar using Bootstrap 4, complete with the "hamburger" icon in the top right corner. It was inspired by one of the Bootstrap examples. However, I encountered an issue where the collapsing and clickable icon functionality worke ...

How to display only a portion of content using UI Bootstrap collapse feature

In my Angular.js application, I currently have a row of buttons that open up new routes to display partial views. Now, I need to modify some of these buttons to trigger a ui.bootstrap Collapse feature with the view inside it. The template code from the ui. ...

Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press. My requirement is to have no animations during the initial page render. While I can successfully slide the box to ...

What steps can I take to ensure the image remains fixed in its position when the browser width is reduced?

Recently, I encountered a challenge with my media query where I wanted to align a button next to another one when the browser width was reduced to 991px. However, instead of staying in place, the button started sliding underneath the other button as I cont ...

Is there a way to prevent the virtual keyboard from covering up input fields on a webview?

I am currently dealing with an issue on my Genero web-app where the webview of an Angular app is not scrolling under an input when it gets the focus. This makes it difficult for users to see what they are typing. Interestingly, loading the page in a regula ...

Navigation bar not visible when scrolling

I recently purchased the Mix Responsive App Landing Page theme from Theme Forest and have had success customizing it, except for when I started removing unnecessary sections. Ever since the removal, the header does not function as intended - it should be h ...

The Bootstrap modal-backdrop dilemma requiring JavaScript intervention

I am encountering some problems with the Bootstrap modal. When I try to open a modal, everything looks good, but when I close it, the screen turns completely black. Upon closer inspection, I found that every time I click on the X to close the modal, there ...

I desire for the website's current state to remain unchanged even after refreshing the page

I run a website that allows users to generate div elements with a button and then input text into them. While I am able to save the text to local storage, I would also like to preserve the divs themselves along with their attributes (such as positioning) ...

Create an Angular material table with expandable rows that become sticky when scrolled past, then automatically unstick once they are no longer in view

Currently, I am working with Angular Material Table v11.1.0 which includes a main row with expandable rows. I want the main row to become sticky once an expandable row is opened and remain sticky while scrolling through the table. My goal is for the main ...

Modifying the color of a placeholder in an HTML input using CSS

Version 4 of Chrome now supports the placeholder attribute on input[type=text] elements (and likely other browsers do too). Despite this, the following CSS code does not affect the color of the placeholder text: input[placeholder], [placeholder], *[pla ...

How to Create a Dynamic CSS Mobile Menu Animation

After checking out some online tutorials, I managed to get a hamburger menu working. However, I encountered an issue with the X icon not being symmetrical after the animation from 3 bars to an X. Here is the comparison: Before: https://gyazo.com/351864d8 ...

Following the incorporation of bootstrap into the website, the column divisions mysteriously vanished

After completing the coding for my website, I had to integrate Bootstrap. However, upon adding the grid to the respective spans, the columns mysteriously disappeared. Any help in identifying what went wrong would be highly appreciated. <div class=" ...