Ringo Blancke
Ringo Blancke

Reputation: 2444

css nested classes, how to not repeat code?

I have a css class that is called button.blue:

button.blue { background-color: blue; ... }
button.blue:active { background-color: darkblue; ... }
button.blue:hover { background-color: lightblue; ... }

To use it, I do the following:

<button class="blue">hello</button>

Now this allows me to have a blue button that has the text "hello" on it. I want to have blue buttons of all different sizes. I don't want to repeat code. What is the best way to do this?

I've tried googling but my question is too vague I think for me to find an answer. I have tried searching for CSS nested classes, grouping, etc. and tried a few random things but nothing seems to work.

Upvotes: 1

Views: 837

Answers (4)

duante
duante

Reputation: 174

You could have some classes that are just sizes like

.big { width: 100px, height: 100px }
.small { width: 20px, height: 20px }

Then you would do

<button class="big blue">hello</button>

Upvotes: 0

Matt Briggs
Matt Briggs

Reputation: 42158

You are able to chain selectors in css. Something like

button.blue.small { height: 20px; }

will only match if it is on a button with a blue class and a small class

Upvotes: 0

Sam Becker
Sam Becker

Reputation: 19636

All your properties from button.blue will be inherited by button.blue:active and button.blue:hover. There is no need to repeat code accept for the properties you wish to change.

Upvotes: 0

LeeR
LeeR

Reputation: 1636

You would just have a class for different widths so

.button_1 {width:100px;}
.button_2 {width:200px;}
.button_3 {width:300px;}
.button_4 {width:400px;}

And so forth. Or some other such naming system. You can have more than one class per element so this will work fine.

<button class="blue button_1">hello</button>

Upvotes: 2

Related Questions