user5714726
user5714726

Reputation: 480

Inherit css property from another property of a different class

Is there a way to get the below to work?

.class1 {
 line-height:20px;
}

.class2 {
  height: class1.line-height;
}

I know that css variables would be the way to go but since it is in experimental phase, it would not be a suitable for our project. Is there any other way?

Upvotes: 2

Views: 4058

Answers (3)

Dai
Dai

Reputation: 155708

Five years later...

I know that css variables would be the way to go but since it is in experimental phase, it would not be a suitable for our project.

As it's 2021 (and no-one is using Internet Explorer 11 anymore, phew, and all the major browsers fully support CSS Variables CSS Custom Properties) so you can now use var().

If you simply want to only define 20px once to avoid repeating yourself in CSS, then set a custom-property on a common ancestor of both .class1 and .class2 elements: most people use html (or html:root or just :root) for this:

:root {
    --my-height: 20px;
}

.class1 {
    line-height: var(--my-height);
}

.class2 {
    height: var(--my-height);
}

Now, if you want .class2 elements to "inherit" their height: from any ancestor class1 elements instead of <html>, then this should work:

:root {
    --my-height: 50px; /* Default value for .class2 elements which are not descendants of .class1` */
}

.class1 {
    --my-height: 20px; /* Redefining the value */
    line-height: var(--my-height);
}

.class2 {
    height: var(--my-height);
}

...or if you want only .class2 descendants of .class1 to use the value:

:root {
}

.class1 {
    --my-height: 20px;
    line-height: var(--my-height);
}

.class1 .class2 {
    height: var(--my-height);
}

But you probably shouldn't be setting line-height anyway - doing-so is a sign that you're misusing display: inline; or vertical-align:;.

Upvotes: 2

mithu
mithu

Reputation: 247

yeah.. you can't use dependencies like that in CSS. you have to use SASS or LESS..

you can do like this in SASS

.class1 {
     line-height:20px;
    }

.class2 {
   @extend.class1
}

Upvotes: 3

Scott
Scott

Reputation: 21888

You can't really use dependencies like that in CSS without a preprocessor such as SASS or LESS. But you can apply more than one class to the HTML.....

<div class="class1 class2"></div>

In this case, class1 would contain the line-height, then class2 would contain any other properties you want to apply to that particular div.

Any similar properties between class1 and class2 would allow class2 to take precedence, since it's loaded after class 1, assuming the CSS hierarchy is logical.

For example:

.class1 { line-height: 1.3; background-color: red;}
.class2 { background-color: blue; }

The div would have a line-height of 1.3x and a background color of blue.

Upvotes: 2

Related Questions