Justin
Justin

Reputation: 86779

CSS div style - should I use class or id?

I have a repeater of div's that look a little bit like this:

<div class="header_div">
    <!-- Content -->
</div>

I want to have the background color of the divs change based on a dynamic property of the content of the div (lets call it the category), but I still want the "header_div" style to be assgined in cases where I dont have a css class for that category. Whats the best way of doing this?

The best way I can think of is to render the category as the "id" of the div and apply styles based on the id, but that strikes me as really messy - standards dictate that the id should uniquenly identify the element on the page and there will definitely be repeats of each category.

Upvotes: 1

Views: 1860

Answers (6)

Kelsey
Kelsey

Reputation: 47736

You can't have duplicate IDs so if you had multiple divs of the same category you would have an issue. Classes should be used when the style needs to be applied for 1 or more items on a single page.

Why not assign the class on databinding of the div based on the category? As your repeater is getting bound, find your div for the item you are binding and assign it.

You could also substitute the div for an asp:Panel and use it's onDataBinding method. It should look exactly like your div.

Upvotes: 0

butterchicken
butterchicken

Reputation: 13883

You could supply multiple styles for the div class:

<div class="header_div mystyle">
    <!-- Content -->
</div>

I believe styles declared later in the declaration override earlier ones. As long as you ensure your custom styles "shadow" those of the header-div, you can always include the header-div element, and it will only have an effect when any secondary style is absent (or empty).

Upvotes: 2

belugabob
belugabob

Reputation: 4460

You're correct about the need for IDs to be unique. There's nothing stopping you from specifying more than one value per class attribute - just separate them with a space.

<div class="header_div category">
    <!-- Content -->
</div>

Just be careful to check what happens when both classes specify different values for the same style - I can't say whether the first or the second would take precedence.

Upvotes: 2

Sean Vieira
Sean Vieira

Reputation: 160015

The simple answer would be to use multiple classes for the <div> so that

<div class="header_div header_red">
    <!-- Content -->
</div>

<div class="header_div header_green">
    <!-- Content -->
</div>

Upvotes: 6

Justin Niessner
Justin Niessner

Reputation: 245459

If it's going to be used repeatedly on the page, it should be a class.

If it's unique on the page, use an id.

Upvotes: 1

amr
amr

Reputation: 1275

Without knowing more about your content, can you not use one of the header tags (<h1> etc)?

You are correct, IDs should be unique and if you want to use the same style more than once then use a class.

Upvotes: 0

Related Questions