Explicit Inheritance in CSS
April 10th, 2008 Filed Under CSS, Javascript, Thinking Out Loud
Many of us might have come across a problem of not able to include an already declared class in another class in CSS.Technically speaking, “Explicit inheritance is not possible in CSS”.I have created a small javascript utility, which, if you include in your page, you can break the ice.It is very simple to use. Just include the js file and write your css in the way you wanted to.To illustrate I will show you the problem first and then the solution:I have the following CSS:
.basic{float:left;margin: 0;padding: 0;}.appBG{background: lime;}#div_1{background: lime; /* REPEAT FROM .appBG */float: left; /* REPEAT FROM .basic */margin: 0; /* REPEAT FROM .basic */padding: 4px; /* REPEAT FROM .basic */}
Ideally inheritance concept says, it should be like this:
.basic{float:left;margin: 0;padding: 0;}.appBG{background: lime;}#div_1{import: .basic;import: .appBG;}
This js utility leverages you with this behaviour of your css.But the syntax is a bit different from what I have shown just now.Please note that the property “import” works only in IE and other browsers don’t support import property in a css class and simply ignore it.So, instead of ‘import’ (shown in the two lines above), we will use an almost never used property called “content” for this purpose.So your code looks something like this:
.basic{float:left;margin: 0;padding: 0;}.appBG{background: lime;}#div_1{content: ".basic, .appBG";font-family: arial;}
But if you still feel that ‘content’ property should not be used for this purpose, please comment me. I’ll have some hack to it, so that you can to use the content property in the same way along with css inheritance(I want to do this anyways).My suggestion is to use this utility if you are building or rewriting your css from the scratch. The cause is that you might have already repeated and duplicated many class properties.I have tested this utility only in Firefox 2.0, Firefox 3.0, IE 6.0, IE 7.0 Please notify me if anyone finds any bugs in any other environment(including different combinations of OS and Browsers)Known Issues:If you disable your javascript, it wont work, but then, that would be same as attaching classes to elements using jquery and disabling javascript.Please let me know what you feel and please comment on the idea.Find the files here to test an example.
Post Linx
Permalink | Trackback |
|
Print This Article |
Comments
Leave a Reply

