Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding duplicate styles in CSS

Tags:

css

I'm trying to teach myself CSS and have the following markup:

<style type="text/css">
#content { display: block; width: 250px; height: 50px; background-color: #330000; }

/* pink */
#one { height: 25px; width: 25px; background-color: #FFCCCC; float: left; margin: 10px; }
/* hot pink */
#two { height: 25px; width: 25px; background-color: #FF0099; float: left; margin: 10px; }
/* tan */
#three { height: 25px; width: 25px; background-color: #CC9900; float: left; margin: 10px; }
/* aqua blue */
#four { height: 25px; width: 25px; background-color: #33FFFF; float: left; margin: 10px; }
/* yellow */
#five { height: 25px; width: 25px; background-color: #FFFF00; float: right; margin: 10px; }

</style>
</head>
<body>

<div id="content">
    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
    <div id="four"></div>
    <div id="five"></div>
</div>

The page is working correctly, but I'm interested in removing the duplicate code within the CSS itself. I.e. have all height, width, float all in one defintion then override the background color for each of the #id values

When I tried:

#content { height: 25px; width: 25px; float: left; margin: 10px }

then put:

#one { background-color: #FFCCCC; }
#five { background-color: #FFFF00; float: right; }

that didn't work.

Basically I'm trying to remove the amount of duplicate markup.

What am I missing?

like image 746
coson Avatar asked Aug 15 '10 19:08

coson


3 Answers

You have to specify the node after #content:

#content div { SAME RULES }
#one { INDIVIDUAL }
#five { INDIVIDUAL }

or you can do this:

#one, #two, #five { SAME RULES }
#one { INDIVIDUAL }

You can also give each of those divs a class name and do

.divs { SAME RULES }
#one { INDIVIDUAL }
like image 178
meder omuraliev Avatar answered Sep 23 '22 14:09

meder omuraliev


You want:

#content div {

i.e. "All the div elements that descend from the element with the id 'content'"

I recommend giving http://css.maxdesign.com.au/selectutorial/ a read.

like image 38
Quentin Avatar answered Sep 23 '22 14:09

Quentin


You could use classes. Define a base class that contains the common properties:

/* Generic class for all four elements */
div.button {  height: 25px; width: 25px; float: left; margin: 10px; }

and then define 1-4 (I'm using classes here as well, as it is the best practice in many cases, but you can carry on using IDs if you want to):

div.one { background-color: #FFCCCC; ... }
div.two { background-color: #FF0099; ... }

and then assign the base class and the specific class:

 <div id="one" class="button one"></div>

the "button one" part will let both classes' properties apply to the element.

like image 22
Pekka Avatar answered Sep 22 '22 14:09

Pekka