Alter the parent container's background color when hovering over the child element, utilizing only CSS

Have you ever wondered about changing the background color of a parent element when hovering over its child? This is a common issue that often leads to closure as a duplicate question. The go-to duplicate is usually one regarding CSS parent selectors, such as this one. While these references are helpful in explaining why parent elements cannot be targeted with CSS, they offer little direction for those experiencing the issue firsthand.

In many cases like this, where the original problem may fall under the XY problem, it's important to find a solution tailored to the specific scenario at hand.

For example, one specific case involves...

How can the background color of the parent be changed when hovering the child?

...and in situations like these, there exists at least one potential CSS solution that could address the challenge effectively.

<div>
  <a href="#">Anchor Text</a>
</div>

Answer №1

Utilizing solely pointer-events and :hover

Checking compatibility of pointer-events: Visit caniuse.com for details. I have personally tested this approach on IE 11, Edge, Chrome, and Firefox.

  • Apply pointer-events: none to the div. This will cause the div to disregard :hover behaviors.

    div {
        pointer-events: none;
    }
    
  • Change the background color of the parent upon hover

    div:hover {
        background: #F00;
    }
    
  • Implement pointer-events: auto on the child element so that the hover effect is only triggered when hovering over the child

    div > a {
        pointer-events: auto;
    }
    

This method functions by triggering the hover state of the div when its child is hovered, with pointer events set to auto exclusively on the child element. This ensures that the parent ignores its own hover pseudo-class.

Example

Important Note: For IE 11 and Edge, the child element must be styled as display: inline-block or display: block in order for pointer events to function correctly.

div {
  height: 200px;
  width: 200px;
  text-align: center;
  pointer-events: none;
}
div:hover {
  background: #F00;
}
div > a {
  pointer-events: auto;
  display: inline-block;
}
<div>
  <h1>Heading</h1>
  <a href="#">Anchor Text</a>
</div>

Answer №2

While CSS doesn't allow you to target parent elements directly, there are alternative methods to achieve the desired effect.

If you want the background color of a parent element to change when a child is hovered over, consider using the spread-radius value of the CSS box-shadow property.

You can create a large spread radius to alter the color of the surrounding area, visually similar to changing the parent element's background color.

div {
    overflow: hidden;              /* 1 */
}

a:hover {
    box-shadow: 0 0 0 1000px red;  /* 2 */
}

/* Additional styles for decoration */
div { 
  height: 150px;
  width: 150px;
  border: 1px dashed black;
  display: flex;
  justify-content: center; 
  align-items: center;
}
<div>
  <a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>

Key Points:

  1. Use overflow: hidden to restrict the child's box shadow
  2. The values for box-shadow are as follows:

<box-shadow> : <offset-x> <offset-y> <blur-radius> <spread-radius> <color>

  • offset-x: horizontal distance from the element
  • offset-y: vertical distance from the element
  • blur-radius: increases the size and transparency of the shadow
  • spread-radius: expands the shadow without fading

In this scenario, the first three values are irrelevant.

To achieve the desired effect, increase the spread-radius significantly and then mask it with the container using overflow: hidden.


What if there's another element in the container?

<div>
  <h2>Hello</h2>
  <a href="http://www.google.com">Anchor Text</a>
</div>

div {
    overflow: hidden;
}
a:hover {
    box-shadow: 0 0 0 1000px red;
}
div { 
  height: 150px;
  width: 150px;
  border: 1px dashed black;
  display: flex;
  flex-direction: column;
  justify-content: center; 
  align-items: center;
}
<div>
  <h2>Hello</h2>
  <a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>

You can assign a z-index to the sibling element.

h2 { z-index: 1; }

Since the elements are within a flex container in this example, they do not need to be positioned explicitly for z-index to take effect. Learn more here.

h2 { z-index: 1; }

div {
    overflow: hidden;
}
a:hover {
    box-shadow: 0 0 0 1000px red;
}
div { 
  height: 150px;
  width: 150px;
  border: 1px dashed black;
  display: flex;
  flex-direction: column;
  justify-content: center; 
  align-items: center;
}
<div>
  <h2>Hello</h2>
  <a href="http://www.stackoverflow.com/">Anchor Text</a>
</div>

Answer №3

One alternative method to simply changing the background of the parent element is to create a pseudo-element for a faux effect. Consider this layout:

.div1 {
  position: relative;
  padding:2em;
  color:white;
}
a {
  color:white;
  font-family:sans-serif;
}
a:before {
  content:"";
  position:absolute;
  left:0;
  top:0;
  height:100%;
  width:100%;
  background:red;
  z-index:-1;
  transition:background .5s linear;
}
a:hover:before {
  background:purple;
}
<div class="div1">
 <div class="div2">
  <h2>Here Some Title</h2>
  <a href="#">Hover Me</a>
 </div>
</div>

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

Is there a way to ensure that a div automatically moves below the main div when it reaches its full length?

I am facing an issue with a foreach statement in jQuery where I am generating Bootstrap cards for each product in a list. The problem arises when attempting to create multiple cards in a row, as the width of the cards becomes too small for the content. I ...

Is there a way to eliminate the white background from a webview display?

Currently, I am facing an issue where I am loading a HTML file into a webview. Both the background color of my HTML file and my activity is black. However, there is a brief white flash at the beginning upon finishing loading due to the white background col ...

storing a value in the browser's local storage

I am in the process of creating a new game that includes a high score feature. The idea is that when the current score surpasses the existing one stored locally, it will be replaced: localStorage.setItem('highScore', highScore); var HighScore = ...

Unable to display Bootstrap 4.3.1 button for Facebook

I'm attempting to incorporate Bootstrap 4.3.1 into my Asp.net Core MVC project, but it appears to be not working. Any suggestions? <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="https ...

It is important for me to retain the values inputted by the user even when the webpage is refreshed

My form entry web page saves data to a local database via another file called "info1.php" after the submit button is clicked. This file also validates the entered data, such as email addresses, and refreshes the page to the home site if the data is invalid ...

What is the method for configuring body attributes in CSS with AngularJS?

Setting the background image of a page using CSS: body { background: url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-backg ...

What steps can I take to ensure that the v-main element occupies at least 70% of the viewport height in Vuetify?

As a newcomer to Vuetify, I am still learning the ropes. One thing I've noticed is that <v-main> automatically expands to fill the space between <v-app-bar> and <v-footer>, taking up the entire viewport height. My concern arises wh ...

Choose several options but only one can be selected for specific choices

How can I allow certain options to be selected either multiple times or only once? Below is the HTML code: <div class="bootstrap-select active_select col-sm-12 col-md-3 col-lg-3"> <select class="selectpicker" id="cron_dow" data-style="btn btn ...

"What is the best way to display an image from a table and then enlarge it to full size when a button is clicked, all

1. Understanding the Concept In my page, I have a table listing various images with unique names that are successfully displayed in the table. My goal is to display the selected image in full screen within a popup window when a button is clicked. 2. Que ...

Error: ShowModalEdituser has not been defined

When implementing this code to display a modal in ASP.NET Core 5, I encountered the following error: Uncaught ReferenceError: ShowModalEdituser is not defined at HTMLButtonElement.onclick(). As a result, the modal does not appear. How can I resolve this er ...

Display a CSS animation upon hovering the mouse

I'm looking to create a unique animation that involves drawing angled and straight lines, along with displaying text from left to right upon hovering over a button. I am relatively new to this concept and would appreciate any guidance. Additionally, I ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Activating a div in React.js using setActive: Step-by-step guide

Currently, I am in the process of developing an application with three menu tabs, each represented by an accordion comprising a menu title and content. The issue I am facing is that when clicking on any menu title, all content divs are displayed simultaneo ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Enhancing the appearance of a specific column with pandas Styling

I have a pandas dataframe and I am trying to customize it by adding a background-color:red to specific columns and then displaying the updated table in an HTML format with the highlighted column visible. This is how my table is structured: import pandas ...

Updating MySQL database with new values from HTML checkboxes

How can I use Ajax to update a MySQL Table value to "yes" when a checkbox is checked and to "no" when it is unchecked? ...

The Uniqueness within Nested Arrays

let unique_segments = segment_arr.filter((elem, index) => { return segment_arr.indexOf(elem) === index; }); In the segment array, each element is represented as [ [x1,y1] , [x2,y2] ] which defines a segment between two points. Can anyone assist me i ...

Using CSS to enhance the appearance of specific sections within my React JSX components

I'm currently working on a small React project where I'm mapping through an array of data to render its contents on the browser. However, I'm facing an issue regarding styling only certain parts of the rendered data and not all of them. The ...

Is there a method to keep the leftmost column in a Google visualization table anchored in place when scrolling horizontally?

I want to replicate the typical google visualization table header row functionality, but I would like it to be focused on the first column instead. It doesn't appear to be a default feature, so I'm curious if it could be achieved using custom CSS ...

Deleting the detailPanel based on a specific condition leads to extra padding

Hello everyone, I am currently working on adding a detailPanel based on a certain condition. However, when I hide it, there is an empty space left behind as shown in this link. The code works perfectly fine when the detail panel is provided: get rowDetai ...