Home > front end >  How to use CSS inheritance with multiple CSS files?
How to use CSS inheritance with multiple CSS files?

Time:07-26

I'm using AdminLTE as my base for styling. There is a class called .sidebar-dark-primary.

In a page I have:

<aside >
</aside>

Now I have a separate CSS file that is loaded after all other files and only if a condition is met.

I need to change the page to be something like:

<aside >
</aside>

And sidebar-custom comes from the separate file.

How do I inherit sidebar-custom from sidebar-dark-primary in one file or to sidebar-light-primary in another file?

CodePudding user response:

You can't. CSS has no feature which lets you write a rule which imports rules from a different ruleset. Nor does it have any feature which changes which classes apply to an element.

In CSS, inheritance means "Take the value of a property from the parent element".

In this example one of the links inherits the font colour from the parent div, while the other doesn't (so has the default link colour the browser applies).

#parent {
  color: green;
}

#inherits {
  color: inherit;
}
<div id="parent">
  <a id="inherits" href="/">
        some text
  </a>
  <br>
  <a id="does-not-inherit" href="/">
        some other text
  </a>
</div>

CodePudding user response:

Using CSS Specificity

Some frontend and CSS frameworks also have a smilar idea. This cannot be solved by simply replacing the class.

You can achieve it by having both classes in the element. This is not really inheritance, but specificity:
MDN: CSS Specificity

See snippet below to illustrate this.

/* main file */

* { margin: 0; padding: 0; }
aside { display: block; color: #999; } /* just for this snippet */
.sidebar { padding: 5px; margin: 10px; border: 2px solid blue; }
.sidebar-dark { background-color: #222; }
.sidebar-dark-primary { background-color: #226; }


/* separate file with customizations */

.sidebar-custom { background-color: #636; border-color: green; }
<html>
<body>

<aside >
Sidebar
</aside>

<aside >
Sidebar: Dark
</aside>

<aside >
Sidebar: Dark Primary
</aside>

<aside >
Sidebar: Dark Primary Custom
</aside>

</body>
</html>

  • Related