Is there a method to apply the background-color of the parent element based on the child class in CSS?

Is there a method to change the parent's background color based on the child's class using CSS?

Here is the sample code snippet: Sample Code If the child has a class of red, the parent should have a red background. If the child has a class of yellow, then the parent should have a yellow background.

<div class="par">
    
    <div class="red">
      hello
    </div>
  </div>



.par{
  background-color:red;
}

.par{
  background-color:yellow;
}
.par{
  width:200px;
  height:200px;
  border:1px solid blue;
  
}


.red{
  width:100px;
  height:100px;
  color:red;
  border:1px solid;
  background-color:green
}

Would it be better to use Javascript or can this be achieved with just CSS?

Answer №1

You can achieve this with the help of the :has() CSS pseudo-class

.par:has(.red){
  background-color:red;
}

.par:has(.yellow){
  background-color:yellow;
}

Link to MDN documentation

**Keep in mind that older versions of Firefox do not support this feature Check browser compatibility

2024 Update: Firefox now supports this feature starting from version no.121 (Released 2023-12-19)

Answer №2

A pseudo element can be used to create a visual effect like this:

.par {
  width: 200px;
  height: 200px;
  border: 1px solid blue;
  position:relative; /* set here and not on child element to maintain position relative to parent */
  z-index:0;
}

.red {
  width: 100px;
  height: 100px;
  color: red;
  border: 1px solid;
  background-color: green;
}
.red::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:inherit;
}
<div class="par">

  <div class="red">
    hello
  </div>
</div>


<div class="par">

  <div class="red" style="background:blue;">
    hello
  </div>
</div>

Answer №3

Cascading Style Sheets (CSS) and DIV elements do not follow the typical parent-child relationship structure. Instead, you must define each variable individually in CSS and then apply those variables to the corresponding DIV elements. To illustrate this process, I have provided an example using your existing code.

.par{
  background-color:red;
  width:200px;
  height:200px;
  border:1px solid blue;
}

.par-yellow{
  background-color:yellow;
  width:150px;
  height:150px;
  border:1px solid;
}

.red{
  width:100px;
  height:100px;
  color:red;
  border:1px solid;
  background-color:green
}
<div class="par">
  <div class="par-yellow">    
    <div class="red">
      helli
    </div>
    </div>
  </div>

Answer №4

Regrettably, CSS does not offer any parent selectors. To work around this limitation, JavaScript is required. One way to achieve a similar effect is by using the following code snippet:

var blueElements = document.querySelectorAll(".blue");
for(var j = 0; j < blueElements.length; j++){
  blueElements[j].parentElement.style.backgroundColor = "blue";
}

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

Retrieving information within a loop through the utilization of a left join操作。

Presently, I am utilizing a while loop to fetch user comments from a MySQL table and applying a conditional class to the buttons within the comment div. Each comment contains two buttons: thumbsup button thumbsdown button I aim to assign the class name ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

How to transform a JQuery button into a dropdown menu

For inspiration, consider this JQuery UI Button example: http://jqueryui.com/demos/button/#splitbutton Now, how can you create a dropdown menu when the small button is clicked? My main concern is the way .button() alters the button's actual appearanc ...

Displaying loading indicators on each button for mapped items in a React application

I am using array.map() to map the comments and replies of comments arrays. {data.comments?.map((comment) => ( <CommentsSection user={user} token={token} thread={data} key={comment._id} comme ...

Switch the background image of a div when hovering over a different div that is not its parent or sibling

I am in the process of building a dynamic portfolio on WordPress and I need some help with a specific functionality. At the top of my page, I have a large banner image, followed by individual thumbnails of my work below. What I want to achieve is the abili ...

Numerous hyperlinks cascading out of the lines

I'm struggling to keep two clickable divs side by side in my code. When I apply the link tag, the divs no longer stay in the same row. Can anyone help me fix this issue? See my current code below: <div class="container col-md-12 pt-5"> < ...

Error encountered during installation of Webpack and webpack-dev-server

I'm currently working on setting up Webpack and Babel for utilizing React without Create React App (CRA). While trying to install webpack-dev-server, I encountered some dependency issues. PS C:\Users\Lebedev\Desktop\projects\ ...

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

Send the result of a successful AJAX request to a partial view

I have added these lines of code, where the success function returns data in the form of [object Object], with attributes like Name, Category, and Description. $.ajax({ url: rootUrl + 'Admin/EditRSS', type: "GET", data: { ...

When applying a blur filter, the fixed navbar vanishes from view

Is there a way to add a blurred background for Bootstrap 4 modals? I had the idea of wrapping everything on the site in one container (navbar, content, and footer), and then applying filter:blur(4px) to it when body.modal-open is activated. However, I ra ...

Exploring the File Selection Dialog in Node.js with TypeScript

Is it possible to display a file dialog in a Node.js TypeScript project without involving a browser or HTML? In my setup, I run the project through CMD and would like to show a box similar to this image: https://i.stack.imgur.com/nJt3h.png Any suggestio ...

Exploring Scope Data Using a Custom AngularJS Directive

We are completely new to the world of AngularJS and are currently facing a challenge in displaying HTML tooltips from a custom directive within Angular. As beginners in this technology, we are struggling to find the right solution for this issue. Initiall ...

Avoiding text from overflowing a DIV when the parent DIV's width is specified as a percentage

After extensively searching through over 20 similar posts, I have not been able to find a solution that works for my specific issue. The layout of some content I'm working with resembles the example provided here: Check out the Fiddle Example In th ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

Is there a way to align text with a certain element and ensure that it remains in place regardless of the screen size?

I need the word "social" to remain in line with the black bars, both on regular devices and mobiles. Although in bootstrap/html it may not align perfectly, it still stays close to the black bars. See example here Here is the code. Even though I can adjus ...

Tips for Setting Up Next.js 13 Route Handlers to Incorporate a Streaming API Endpoint via LangChain

I am currently working on establishing an API endpoint using the latest Route Handler feature in Nextjs 13. This particular API utilizes LangChain and streams the response directly to the frontend. When interacting with the OpenAI wrapper class, I make sur ...

Is concealing content using Javascript or jQuery worth exploring?

While I have been hiding content using display:none; in css, there are concerns that Google may not like this approach. However, due to the needs of jQuery animations, it has been necessary for me. Recently, I have come across a new method for hiding conte ...

An error occurred while trying to access the property 'send' which is undefined

I am currently facing an issue while attempting to send data to the router from an external script. The error message that I receive is TypeError: Cannot read property 'send' of undefined Below is the code snippet: app.js var Cake = require(&a ...

Create an XPath by utilizing the class and text attributes of a div element

Struggling to create a relative xpath for use with webdriver, none of the ones I've attempted seem to be working. Here is my Web Element: <div class="pa-PrimaryNavWidget-hyperlink" style="color: rgb(255, 255, 255); cursor: default; background-col ...

Why does the browser indicate that a GET request has been sent but the promise does not return anything?

Having trouble with a puzzling issue and unable to find any solutions online. I am attempting to make a basic HTTP get request to receive a JSON object from an API I created (using express+CORS). I have experimented with both Axios and VueResource, yet en ...