Vonder
Vonder

Reputation: 4059

Style common group of divs in one css statement

I have a few divs created dynamically in Javascript.I was wondering if it is possible to style them all at once.

#somediv {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

#somediv2 {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

...and so on (this can be even 50 divs)

I would like to change this to something like:

 #somediv* {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

Upvotes: 0

Views: 280

Answers (5)

swestrup
swestrup

Reputation: 4209

This is what the class attribute was created to handle. Give all of your divs the same class and you can say something like:

.divclass {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

But if you REALLY need to do what you asked, you can use a new form of selector. The following will match all IDs that start with 'somediv', but this won't work on older browsers:

[id^=somediv] {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

Upvotes: 1

David Thomas
David Thomas

Reputation: 253446

I'd personally suggest using a class, since that's what they're for; you can, though, do it as you want to:

div[id^=somediv]
{
/* css styles */
}

Using the CSS starts-with selector (http://reference.sitepoint.com/css/css3attributeselectors), although it relies on CSS 3 (I think) implementation in your user/audience.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630579

If they are going to be styled exactly the same, use a class, look here for the difference:

.divClass {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

Then your divs are like this:

<div id="somediv" class="divClass"></div>
<div id="somediv2" class="divClass"></div>

Just edit your script to include the class attribute, by far the easiest solution...and this is exactly what classes are for :)

Upvotes: 4

rfunduk
rfunduk

Reputation: 30442

Give your dynamically created div's a class, then style the class. Or maybe if you're inserting your new divs into a container you could just select based on that:

<div id='stuff_goes_here'>
  <!-- ... dynamic divs will go here ... -->
</div>

and then:

#stuff_goes_here div {
  /* ... styles ... */
}

Upvotes: 4

rpiontek
rpiontek

Reputation: 39

#somediv, #somediv2 {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

Upvotes: 0

Related Questions