Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in CSS properties?

Tags:

css

Sorry, but no matter how often I read it, I just don't grok it.

I have declared

.submit_button  
{  
  font: 12px Arial;  
  margin:0px;  
  padding:2px;  
}

and now I want to declare centered_submit_button which inherits from submit_button and adds margin-left:auto; margin-right:auto;

Please take pity on me ...

like image 236
Mawg says reinstate Monica Avatar asked Jul 26 '26 07:07

Mawg says reinstate Monica


2 Answers

Unfortunately, vanilla CSS doesn't have any notion of inheritance, but you can achieve what you need with this:

.submit_button, .centered_submit_button
{
    font: 12px Arial;  
    margin: 0px;  
    padding: 2px; 
}

.centered_submit_button
{
    margin-left: auto;
    margin-right: auto;
}

This is probably all that you need, but as scurker mentioned, there are CSS-enhancing tools such as LESS that provide inheritance-like constructs as well as many other nice features that can improve your quality-of-life as a web developer.

In this case, LESS is ironically more verbose, but arguably more expressive:

.button ()
{
    font: 12px Arial;
    margin: 0px;  
    padding: 2px; 
}

.submit_button
{
    .button;
}

.centered_submit_button
{
    .button;
    margin-left: auto;
    margin-right: auto;
}

Another similar tool is Stylus, which does most of what LESS does, but also has a very indifferent attitude about using punctuation in your syntax:

button()
    font 12px Arial
    margin 0px
    padding 2px

.submit_button
    button

.centered_submit_button
    button
    margin-left auto
    margin-right auto

Both LESS and Stylus have client-side JavaScript implementations, so you have the option to host your .less or .stylus files directly or to compile them on the server and host the resulting CSS.

like image 182
namuol Avatar answered Jul 28 '26 20:07

namuol


It doesn't work quite like that. There is no concept of inheritance in that sense, in CSS. However, what you CAN do, is define the common attributes of .submit_button and .centered_submit_button, and then redefine the things you want to do differently, for only .centered_submit_button, like this:

.submit_button, .centered_submit_button
{  
  font: 12px Arial;  
  margin:0px;  
  padding:2px;  
}

.centered_submit_button
{
  margin-left:auto;
  margin-right:auto;
}
like image 40
crimson_penguin Avatar answered Jul 28 '26 20:07

crimson_penguin