proseidon
proseidon

Reputation: 2305

How can I separate my stylesheets by class?

What I mean to say with this is, if I have a page with two divs, and I want each div to have a separate style, what way would I go about this?

Example:

div{ background: red;} // apply this style to one div.
div{ background: blue;} //apply this style to another div.

I realize it would be possible to just add a class to each div, but what if I expand it? What if I want a whole section of my page with a lot of different attributes to use one part of the stylesheet, and another whole section to use another part?

Upvotes: 0

Views: 47

Answers (3)

Nemo64
Nemo64

Reputation: 2683

As far as I understand it you want for example every div in your header to be green while every div in your footer is supposed to be red.

#header div{ background-color: green; }

And than

<div id="header">
    <div>I'm green</div>
</div>

You can also use more complex selectors to helpt you solve special cases, take this example:

#header div{ background-color: red; }
#header > div{ background-color: green; }

And than

<div id="header">
    <div>
        I'm green...
        <div>...and I'm red</div>
    </div>
</div>

Microsoft has a great overview of what selectors are available. There examples are sometimes a little weak but its something.

Upvotes: 2

JLRishe
JLRishe

Reputation: 101680

You can do this:

.firstSectionType div{ background: red;} // apply this style to one div.
.firstSectionType span { color: blue; }
.secondSectionType div{ background: blue;} //apply this style to another div. 
.secondSectionType span {color: red; }

Then if your HTML looks like this:

<div class="firstSectionType">
    <p><span>Hello</span></p>
    <div>This has a red background and <span>this is blue text</span></div>
</div>
<div class="secondSectionType">
    <p><span>Hello</span></p>
    <div>This has a blue background and <span>this is red text</span></div>
</div>

the divs and spans in the corresponding secions will be formatted accordingly.

The CSS above requires you to repeat .firstSectionType or .secondSectionType in each rule, but a CSS preprocessor like LESS will allow you to rewrite it like:

.firstSectionType
{
    div{ background: red;} // apply this style to one div.
    span { color: blue; }
}
.secondSectionType 
{
    div{ background: blue;} //apply this style to another div. 
    span {color: red; }
}

Upvotes: 1

laurent
laurent

Reputation: 90776

You can simply prefix the CSS rules with the ID or class of the section. For example:

#section1 h1 {
    color: red;
}

#section2 h1 {
    color: blue;
}

and basically prefix every rule with either #section1 or #section2 depending on the containing section.

Upvotes: 3

Related Questions