Roman
Roman

Reputation: 9441

Can a css property be referenced from another css rule?

I have found many answers from several years ago (like this) that say "no". However, have things changed? For example, is something like this now possible:

#property1 {
    height: 100px
}

#property2 {
    height: calc(#property1.height + 50px)
}

I know that I can do this with jquery, but is it possible to do in css only?

Upvotes: 0

Views: 71

Answers (4)

Jack
Jack

Reputation: 9388

The future is ... almost here.

As others have suggested, a preprocessor can be used to accomplish this. If, however, you're the type who lives on the bleeding edge while staying up all night reading draft specs, then you'll be excited about drumroll CSS variables!

Go, check it out here:

http://dev.w3.org/csswg/css-variables/

(MDN if draft specs don't get your juices flowing)

Awesomely enough, there's an example that is similar to your question!

one   { --foo: 10px; }
two   { --bar: calc(var(--foo) + 10px); }
three { --foo: calc(var(--bar) + 10px); }

Great, right?!

Well, the bad news...unfortunately, support is, well, terrible.

http://caniuse.com/#feat=css-variables

But, in the future (and fingers crossed), we'll have native CSS variables!

Upvotes: 1

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

Yes! but o nly if the secound div is a child

#property1 {
    height: 100px;
    width:320px;
    background:red
}

#property2 {
    height: calc(100% + 50px);
    width:100%;
    background:green
}
<div id=property1>
    <div id=property2></div>
</div>

if you don't want to use it as a child then it is time for you to learn a CSS pre-processor such as Less or Sass

Upvotes: 0

avcajaraville
avcajaraville

Reputation: 9084

No with pure css, but you can do that with a preproccessor like sass or less.

Here an example written on sass:

$height: 100px;
#property1 {
    height: $height;
}

#property2 {
    height: $height + 50px;
}

PS: dont listen to "less" people, they are just wrong :D

SASS

Upvotes: 1

Florin Pop
Florin Pop

Reputation: 5135

No, that is not possible in simple css, but you can do something like this in LESS:

@size: 100px;
#property1 {
  height: @size;
}
#property2 {
  height: @size + 50px;
}

More to find out here.

Upvotes: 2

Related Questions