Preventing parent properties from overriding descendants is a key part of maintaining a hierarchical

I found a css file online that I'm using for a website I'm building, but I am only incorporating certain components from it. The issue is that the global styles in this css file are overriding all the global styles on my website. My solution was to wrap these global styles and make them descendants of a class, which I then set as the parent class of my component. Here's an example:

h1 {
  color: red;
}

.text {
  color: blue;
}

However, all h1 tags on my page turned red. So, I wrapped the global styles and modified the new css like this:

.parent-class h1 {
  color: red;
}

.text {
  color: blue;
}

And adjusted my html accordingly:

<h1>This should not be affected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>How's it going</h1>
</div>

The initial change worked fine with the top h1 unaffected by the global css. Yet, now the problem arises where the text class doesn't override the global h1 style, resulting in "Hello" also being red.

I thought about the order of appearance in the css file and the usage of classes over IDs, but couldn't find the root cause. If the issue lies in having multiple rules under .parent-class h1, is there a way to resolve it?

One option might involve individually wrapping all occurrences of child elements within the parent, like .parent-class .text. However, this would be incredibly time-consuming given the extensive length of the css file. Is there another solution to tackle this challenge?

If not, is there a method to group multiple blocks of code under a parent rule, perhaps utilizing a format like this:

.parent-class {
  .text {
    color: blue;
  };
  h1 {
    color: red;
  };
}

Is such a structure feasible or does it require a different approach?

Answer №1

Ensure that your second selector maintains equal or higher specificity by combining it with another element. One way to achieve this is by adding nth-child(n), which will not alter the behavior of your selector but will effectively boost its specificity:

.parent-class h1 {
  color: red;
}

.text:nth-child(n) {
  color: blue;
}
<h1>This text remains unaffected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>Goodbye</h1>
</div>

You also have the option to duplicate the class name:

.parent-class h1 {
  color: red;
}

.text.text {
  color: blue;
}
<h1>This text stays unaffected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>Goodbye</h1>
</div>

Answer №2

To efficiently update multiple stylesheet rules sourced from another location, the CSSStyleSheet API can be utilized for deleting and inserting rules:

const styleSheet = document.styleSheets[0]
const rules =  Array.from(styleSheet.cssRules).map(r => r.cssText) // retrieve rule texts
rules.forEach(() => styleSheet.deleteRule(0)); // remove existing rules from the stylesheet
rules.forEach(cssText => styleSheet.insertRule(`.parent-class ${cssText}`)) // create new rules with the namespace
h1 {
  color: red;
}

.text {
  color: blue;
}
<h1>This should not be affected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>How's it going</h1>
</div>

If targeting a specific case, you can employ the :not() pseudo-class to exclude styling for h1 elements with the class .text:

.parent-class h1:not(.text) {
  color: red;
}

.text {
  color: blue;
}
<h1>This should not be affected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>How's it going</h1>
</div>

Answer №3

Here is an example of how to apply the !important rule:

h2 {font-size: 20px;}

.paragraph {font-family: Arial, sans-serif !important;}

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

Having trouble with my phonegap app not allowing me to open any

I've just embarked on creating my first phonegap application using an HTML5 mobile website template. After deploying it, I noticed that the external links are not working within the app. Clicking on a link doesn't seem to do anything. To addres ...

using sass to nest multiple classes

In an attempt to utilize nested classes with Sass, I am working on a styling code that displays a button on hover. Here is the structure of my SCSS: .item{ border-bottom: 1px dotted #ccc; text-indent: 50px; height: 81%; padding: 2px; text-transf ...

How do I eliminate excess space following the resizing of the Material UI Drawer component?

I adjusted the size of my MUI drawer to a specific width and now I am facing an issue where there is extra space left after resizing. This results in a margin-like space between the drawer and the Lorem Ipsum text content. My goal is to eliminate this rema ...

Avoid allowing text to spill out of the designated container

Hey there, I've run into this issue twice now and I can't seem to find a solution for the second occurrence. The first time it happened with an image, I used max-height and width to prevent it from overflowing the div when zoomed in. But now, for ...

Reposition icons accordingly while incorporating a new set of icons

After creating a new icon set font, I noticed that the icons are not positioning correctly and appear smaller than expected when loaded: https://i.stack.imgur.com/1OsAL.png https://i.stack.imgur.com/zmLQq.png I attempted to adjust the .icon class by add ...

The jQuery ellipsis extension is incompatible with the "max-height" property

Is it possible to use this plugin with the "max-height" css property? Currently, it only works with a specific height defined but not with max-height. Is there a way to make it compatible with max-height as well? (function($) { $.fn.ellipsis = f ...

Is it possible to remove the address bar from appearing on a browser when a page loads?

I am in the process of developing a customer wifi landing page, and although we have made progress with ensuring it is the first page that loads, I want to take it a step further. My goal is to require customers to agree to our usage policy before gaining ...

Mobile Size Setting

Could someone please explain to me why when I test this code on Google Chrome using the mobile emulator for Galaxy S3, it displays the correct size (640x360), but when I try to load it on my actual Galaxy S5 or any other device, the size is different from ...

Adjusting table dimensions according to webpage dimensions

When looking at the image below, you will notice a div that contains a table with some content. However, when resizing the web browser's page, the table goes beyond the boundaries of the div. My goal is to reduce the size of the table as it scales do ...

Adjusting the background element of a fullpage.js layout during resizing and customization

Is there a way to make the background image responsive on a fullpage.js page, specifically for mobile and tablet devices? How can I ensure that a specific part of the image stays at the center of the page when resizing? For instance, in the provided imag ...

What is the best way to extract a piece of text and incorporate it onto my website?

I'm currently attempting to extract the URL from a page on Steam. My goal is to obtain the picture URL of any user who visits it. Here is the JSON code provided by Steam when requesting a user's information: { "response": { "players": [ ...

Steps for deactivating the submit button once confirming the presence of the username and email

When using AJAX to verify the existence of an email or username in the database, I want to deactivate the submit button if either one (or both) already exist. Currently, I have successfully changed the input border color but I am facing a challenge with t ...

modifying input field with radio button selection in Jquery

Is there a way to set the input field to have a default value and then change it, or disable it with a different value? $("#tax").value(19).prop("disabled",false); $("#tax").value(0).prop("disabled",true); <script src="https://ajax.googleapis.com/aj ...

Switch the background color when a radio button is chosen

For my quiz on test practice with an array of questions, each question includes five radio buttons, but only one is correct. Initially, all five options have a gray background. Upon selecting a wrong option, it changes to red. If another incorrect option i ...

Trigger a jQuery function upon clicking a button

I am attempting to create a jQuery function that can be called independently, and then trigger the function when a click event occurs. Below is the code I have put together: HTML: <input type="text" class="form-control email_input" name='email&ap ...

What is it about the phone screen that makes media content so captivating?

My phone has a resolution of 2280x1080. I noticed that when using the following code, the background color changes to blue on my phone: @media (max-width: 500px) { body { background-color: blue; } } Interestingly, this feature stops working once "compute ...

How can you make the contents of a <DIV> expand?

Picture a scenario where I have a navigation bar in the header of my web page, consisting of several links. What I want is for these links to expand horizontally to fill the parent container without me having to hard-code based on the number of links. In o ...

How to hide offcanvas navigation bar with one click in Bootstrap 5

There was an issue with a Bootstrap 5 project where the offcanvas menu would remain open after clicking on an anchor link. Is there a way to automatically close the offcanvas menu after clicking on an anchor link? <nav class="navbar fixed-top py ...

Deactivate the Autofill feature on Google Toolbar

Dealing with the Google Toolbar's autofill feature has been a constant frustration in my web development journey over the years. I have resorted to creating a timer control to monitor changes, as the developers overlooked firing change events on contr ...

Swapping React components within a list: How to easily change classes

For my latest project, I am building a straightforward ecommerce website. One of the key features on the product page is the ability for users to select different attributes such as sizes and colors. These options are represented by clickable divs that pul ...