Search code examples
cssstylesheet

CSS - Extending class properties


I'm pretty new to CSS and have been finding my way around so far. I am creating these button like links with shadows and stuff. Now there are several such buttons required on the site - everything about the buttons is same - except few properties change like width and font size.

Now instead of copying the same code - over and over for each button - is there a way of extending the button and adding just the properties that change.

Example of two buttons - css

.ask-button-display {
background: #8BAF3B;
border-radius: 4px;
display: block;
letter-spacing: 0.5px;
position: relative;
border-color: #293829;
border-width: 2px 1px;
border-style: solid;
text-align:center;
color: #FFF;
width:350px;
font-size: 20px;
font-weight: bold;
padding:10px;
}


.ask-button-submit {
background: #8BAF3B;
border-radius: 4px;
display: block;
letter-spacing: 0.5px;
position: relative;
border-color: #293829;
border-width: 2px 1px;
border-style: solid;
text-align:center;
color: #FFF;
font-weight: bold;
width:75px;
font-size: 12px;
padding: 1px;
}

And this is how I'm currently using it in my html

<a href="/" id="ask-question-link" class="ask-button-display">Ask a Question</a> <a href="/" class="ask-button-submit" id="ask-button-submit">Submit</a>

So I'm wondering if there is a cleaner way to do this - like

.button {
/* PUT ALL THE COMMON PROPERTIES HERE */
}

AND THEN SOMEHOW EXTEND IT LIKE
.button #display {
/* THE DIFFERENT PROPERTIES OF Display BUTTON */
}

.button #ask {
/* THE DIFFERENT PROPERTIES OF Ask BUTTON */
}

But I'm not sure how to do this. Thanks for your inputs


Solution

  • You can add multiple classes to one element, so have one .button class which covers everything, then a .button-submit class, which adds things in.

    For example:

    .button {
        padding: 10px;
        margin: 10px;
        background-color: red;
    }
    
    .button-submit {
        background-color: green;
    }​
    

    See a live jsFiddle here

    In your case, the following should work:

    .button {
        background: #8BAF3B;
        border-radius: 4px;
        display: block;
        letter-spacing: 0.5px;
        position: relative;
        border-color: #293829;
        border-width: 2px 1px;
        border-style: solid;
        text-align:center;
        color: #FFF;
        width:350px;
        font-size: 20px;
        font-weight: bold;
        padding:10px;
    }
    
    
    .button-submit {
        width:75px;
        font-size: 12px;
        padding: 1px;
    }​
    

    See a live jsFiddle here