Recently, a cousin of mine (also a programmer) lamented on Facebook that he wished that CSS supported inhertiance in the manner as many programming languages. It turns out that there is “pseudo-inheritance” (my term) possible in CSS. Here’s a quick-n-dirty.

CSS offers an “@import” rule. This allows you to import one CSS file into a second CSS file. So “base.css” can be “@imported” into “descendant.css” using syntax such as :

@import(base.css);

CSS classes defined in base.css are defined in descendant.css by virtue of base.css being @import-ed in descendant.css.

For example, consider this simple base CSS file (base.css):

.custom_text {color:blue;font-family:sans-serif;}

Next, consider a descendant CSS file with this content (descendant.css):

@import(base.css);
.custom_text{font-style:italic;}

Referencing descendant.css in your HTML and applying the “custom_text” class to a text element will yield an element displaying blue, italic text in a sans-serif font.

Recently, I had a project in which this pseudo-inheritance came in very handy. There were three distinct areas of the site in my project. The three areas have many CSS properties in common, with some distinct differences between them.

Rather than create three separate CSS files with nearly identical content, I created a base CSS file and three descendant CSS fles. This has made maintenance of the site much easier, as most of the CSS modifications are done in the base CSS file. Modifications to the three descendant files are limited and makes testing much simpler since we don’t have to regression test the entire site, when something changes in a descendant file. Just the handful or pages that reference the descendant in question.

There are some drawbacks and limitations (minor). But for most modern browsers (even IE 5.5+) @import can be used effectively.

Here are some links to discussions on its use:

W3 definition of @import: http://www.w3.org/TR/CSS2/cascade.html#at-import

Mozilla Developer site: https://developer.mozilla.org/en-US/docs/Web/CSS/@import#Browser_compatibility

Stack Overflow: http://stackoverflow.com/questions/147500/is-it-possible-to-include-one-css-file-into-another

I hope you are able to make use of this interesting CSS directive. I know that it has been handy for me.


If you found this useful, consider helping me maintain this site.


Leave a Reply

Your email address will not be published. Required fields are marked *