0

Can I create "class inheritance" in CSS? Something like:

.squareButton {width:20px; height:20px; margin:1px solid;} .squareRedButton {.squareButton; background:red;} 
2

2 Answers 2

2

Yes you can, just apply the desired CSS to both the class you need :

.squareButton, .squareRedButton { width : 20px; height : 20px; margin : 1px solid; } .squareRedButton { background : red; } 

Note

You can pass through HTML to use several classes to perform an inheritance like following :

CSS

.squareButton { width : 20px; height : 20px; margin : 1px solid; } .squareRedButton { background:red; } 

HTML

<button class="squareButton squareRedButton">MyButton</button> 
5
  • or give your DOM element two classes (<div class="squareButton red">)
    – Thilo
    CommentedNov 17, 2015 at 12:10
  • I would rather use your solution @Thilo because it better illustrate this concept of inheritance, so my answer was the CSS way.
    – Anwar
    CommentedNov 17, 2015 at 12:11
  • The third way would be to use a preprocessor like SASS or LESS to augment the squareRedButton class with everything you want to inherit.
    – Thilo
    CommentedNov 17, 2015 at 12:15
  • But this gets rather complicated if I have a larger tree of inheritance, with larger depth... need to repeat many classes many times...
    – Free Bud
    CommentedNov 17, 2015 at 12:18
  • Since CSS is not a programming language, it doesn't have this notion of pure inheritance of objects. Only cascading styling system through the first solution I gave you. But if this three of style is getting harder, follow @Thilo answer, using preprocessing CSS like SASS or LESS to be closer to a real programmed system with high level of style complexity.
    – Anwar
    CommentedNov 17, 2015 at 13:13
0
.squareButton{ width : 20px; height : 20px; margin : 1px solid; } .bg-red { background : red; } <div class="squareButton bg-red"> 

This is the short code way of doing.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.