How to inherit css from grandparent tag?

I have a two-level nested div, and I want to apply a div containing the class "c" with the same div width with class a. If he is a parent, I think inheritance will do the job. But what to do in this case?

HTML code:

<div class="a"> <div class="b"> <div class="c"> </div> </div> </div> 

CSS CODE

 .a{ width:600px; } .b{ width:80%; } .c{ //needs to inherit width property set for class a without directly mentioning it as 600px } 
+7
css
source share
3 answers

Unfortunately you cannot do this in pure CSS, by default the child never inherits width , you need to specify it, yes, by default it will span 100% if you use a block level element like div or p , but inorder to inherit (re use) property grand parent you can use CSS preprocessors such as LESS or SASS ..

So, if you want to do this in SASS, we can do something like

 .a { width: 600px; } .b { width: 80%; } .c { @extend .a; //This is still not an inheritance, you are simply pulling in all the //properties defined in .a to this class } 

So, here he selects all the properties from .a to .c . But here's the trick when you use notation . in SASS, it literally prints the .a block, so if you want to use it only for @extend , you can write this selector instead

 %a { width: 600px; } .c { @extend %a; } 

Here, SASS no longer prints .a , but only .c . You can link to white papers for more SASS @extend

You can also define variables in SASS, so the definition is with $base-width: 600px; and reusing it through may make sense. If you still want to stick with traditional CSS, I would recommend that you declare several classes in the same way as Manoj suggested, but I would not do this as if you were declaring any properties in .a and the same in .c , everything will start to get confused.

+5
source share

You can add several classes in the grandchild div to include properties of a in c.

Also setting 80% for .b will result in 80% of 600px = 480px for .c You need to change it to 100%.

 .a { width: 600px; } .b { width: 100%; } 
 <div class="a"> <div class="b"> <div class="ac"> I am 600px wide. </div> </div> </div> 
+2
source share

The following is an opportunity and, as such, may be useful, but not recommended, as the best way for most cases. It reminds me of problems with em units.

Using a preprocessor with variables is the best way, although this is not entirely inheritance and is not pure css.

 .a { width:600px; } .b { width:80%; } .c { width: 125%; } 

Where .c { width } is 100 / .b { width } * 100 , or in the example 125%.

See an example here on JSFiddle

You still inherit from the parent, but the parent, in turn, inherits from grandfather and grandmother.

+2
source share

All Articles