0

Can CSS have inheritance like OOP?

For example I have this style

.myButton {
background-color:#ffec64;
border:1px solid #ffaa22;
}

Can I define parent for color attributes? Something like

myYellow: #ffec64

So that in every styles I will just use

.myButton {
background-color:myYellow;
border:1px solid #ffaa22;
}

So that changing yellow color will only be on myYellow attribute not for every background-color attributes.

Thanks in advance

3
  • 1
    Use LESS : lesscss.org or SASS : sass-lang.com Commented May 21, 2014 at 3:30
  • Hmm so by default CSS doesn't have this kind of feature is it? Commented May 21, 2014 at 3:35
  • no, but you will have much easier life using SASS. Commented May 21, 2014 at 3:38

2 Answers 2

3

This is not possible when using CSS alone.

You can do this by using a css preprocessor like LESS or SASS. These allow for variables, mixins, functions and many other techniques that allow you to make CSS that is more maintainable, themable and extendable.

Once you have written your LESS or SASS you then need to compile it to standard css (in the case of LESS this can be done client-side).

Sign up to request clarification or add additional context in comments.

Comments

2

You may need to use CSS Pre Processors like LESS or SASS.

Example Using LESS variables

@myYellow: #ffec64;

.myButton {
    background-color: @myYellow;
    border: 1px solid #ffaa22;
}

or even you can use LESS mixin to inherit css class.

.myCommonButton {
    background-color: @myYellow;
    border: 1px solid #ffaa22;
}

.myButton {
    .myCommonButton;
    color: black;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.