Can we implement CSS that is based on the latest ancestor?

Incorporating CSS, my goal is to implement varying styles to the element labeled with the class test. However, the style should differ based on whether it is situated within an element of class a or class b:

<div class="a">
  lorem
  <div class="b">
    ipsum
    <div class="test">&nbsp;</div>
  </div>
</div>

It should receive a distinct style compared to

<div class="b">
  lorem
  <div class="a">
    imsum
    <div class="test">&nbsp;</div>
  </div>
</div>

However, upon applying the style

.a .test { background-color: red; }
.b .test { background-color: blue; }

both end up with a blue background: https://jsfiddle.net/emk5fozg/4/

I desire the second one to display in red, since it is a more direct child of .a than .b.

The issue lies in the fact that utilizing the child selector > is not viable, as there could potentially be approximately 7 layers of divs in between the pertinent ones. (I have counted them, so please refrain from inquiring about the abundance.)

How can I allocate styles to elements based on their closest ancestor?

To clarify: I strictly intend to style the .test divs themselves, without affecting any surrounding elements. There are numerous other elements preceding and succeeding them that should remain unaffected by the style.

Answer №1

If you want to achieve that effect, simply include one more selector in your CSS code:

https://codepen.io/johndoe/pen/XzVpQW

.x .y .z {
  color: green;
}

.y .x .z {
  color: orange;
}

Answer №2

One way to tackle this is by following these steps:

.c .test, .d .c .test{ background-color: green; }
.d .test, .c .d .test { background-color: yellow; }
<div class="c">
  <div class="d">
    <div class="test">&nbsp;</div>
  </div>
</div>

<div class="d">
  <div class="c">
    <div class="test">&nbsp;</div>
  </div>
</div>

Answer №3

Both are identical. It's as if you initially set it as red:

    .test {
        background-color:red;
          }

and then switched it to blue. The only way to keep the red color is to write it this way:

    .b .test { background-color: blue; }
    .a .test { background-color: red; }

Answer №4

To make it simple, you can specify the entire hierarchy like this:

.b .a .example { background-color: red; }
.a .b .example { background-color: blue; }

For even more precision, you can specify the direct parents:

.b > .a > .example { background-color: red; }
.a > .b > .example { background-color: 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

The Angular factory function was unable to be initialized

I recently started learning how to integrate Angularjs with ROR using this helpful tutorial While working on adding a new function to retrieve all posts from the database, I encountered a problem. The page no longer loads when I run the code and the HTML ...

Trouble with HTML img srcset functionality?

I'm currently working on implementing responsive images, and while everything seems to be functioning correctly in the latest version of Firefox, I'm encountering issues with Safari and Chrome. <img src="/images/pages/arrivals/02_exterio ...

"Resolving the duplication issue of a textbox in Phonegap app

I encountered a strange issue recently. While trying to focus on the textbox in my PhoneGap application using touch, I noticed that there are actually 2 textboxes appearing. Please refer to the attached image: ...

Pass the code from the webpage to the PHP script

On my website, I have implemented a feature using JavaScript that dynamically changes the page content. Now, I am looking for a way to send this updated content to a PHP script. How can I achieve this functionality? ...

Jquery Droppable issue arising with dynamically added DIVs

I am facing a similar issue as described in this question and this one I am trying to implement drag-and-drop and resize functionality. It is working fine for static elements, but I encounter issues when adding dynamic divs. The resize property works prop ...

Having trouble with the ::after element in my React component for my latest React 3D portfolio project

For my portfolio project, I am following a tutorial by LamaDev (https://www.youtube.com/watch?v=qALsVa-V9qo&t=2334s&ab_channel=LamaDev). At around timestamp 36:40, he creates a ::after selector which is not working for me, even though the rest of t ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

What is the best way to choose the element directly beneath a specific element using jQuery?

I am facing a challenge where I need to manipulate HTML content using only jQuery, without changing the original structure. The requirement is to display and slide down content with a specific class (current) upon clicking on an h1 tag. However, I am strug ...

When CSS Display table is resized at media query breakpoints, it causes other cells to disappear

This is a discussion on creating a responsive image gallery website with images of different sizes and no margins or paddings. The issue at hand is that the .showcase class hides at a specific @media breakpoint when resizing, but there is a desire to displ ...

Navigation Menu in Motion

I'm currently working on a website for my F1 in Schools team and I'm looking to implement a feature where the button in the navigation bar changes its background color and font color when that section of the page is active, even while scrolling o ...

Activate the overflow feature within native-base cards

I have a unique design element on a website that showcases an image overflowing off a card. The image has a negative margin-top of -50, creating this effect. Now I'm trying to replicate this design in react-native using native-base components. Here i ...

The Android WebView experiencing issues with the functionality of the Hamburger Menu

I'm facing an unusual issue with the Android WebView in my app. The hamburger menu on my website works perfectly fine on my mobile browser, but when I try to open it in the Android WebView, it does not fully expand to show the menu items. I have trie ...

Arranging a child element within a parent element by placing the child div on the right side of the parent div

I am struggling with positioning a child .div containing rotating images to the right side of its parent (header) .div. I am utilizing the flexbox model for layout purposes. Despite my efforts, the solutions I have come across so far have not yielded the ...

Default values for CSS variables: only apply if the variable has not been previously defined

My Web Component relies on the power of CSS variables. To set default values for these variables is crucial. With their wide usage across multiple files, it's essential to define them once and for all. The initial approach turns the text color to b ...

The property cannot be set for an undefined element in Jquery UI slider tabs

There seems to be some extra space at the bottom of the slider tabs between the navigators and content. Additionally, I am facing a challenge in making the page responsive as the content size does not adjust when I resize the window. To see the changes, I ...

CSS: Achieving Full Container Width Text with Respect to Another Container's Height

Hello, I am facing a very specific issue that I can't seem to resolve: I have two containers (ion-card) and I want them to always be the same height. I was able to achieve this by following the solution provided here: https://i.sstatic.net/he8O7.png ...

Exploring the utilization of CSS host selectors with Angular4 to target direct child elements

Within my app.component.css file, I currently have the following code snippet: * ~ * { margin-top: 24px; } This rule actually adds some top margin to all elements that come after the first one. However, this is not exactly what I intend to achieve. My ...

Is it necessary for HTML "buttons" to follow the same box-model as other elements?

I recently encountered an issue with the button element and the input element when using a type of button. In both Firefox and Chrome, I noticed a behavior that seems like a bug in recent releases. However, as form elements often have exceptions to W3 rule ...

Having trouble selecting a URL tag that was dynamically created using JQuery by its class?

While working on implementing a TagCloud for my website, I encountered an issue with using JQuery to alert me about the selected link. Even though the links are being generated correctly and assigned the 'tagLink' class, when I attempt to determi ...

How can one generate an HTML element using a DOM "element"?

When extracting an element from an HTML page, one can utilize a DOM method like .getElementById(). This method provides a JavaScript object containing a comprehensive list of the element's properties. An example of this can be seen on a MDN documentat ...