Hintswen
Hintswen

Reputation: 4007

apply css to nested divs

I use the following code on my page:

<div id="itemstable" class="item_type1">
...other divs here...
</div>

And in my CSS file I have this code:

.item_type1 div {
    background-image: url(images/type1.giff);
}

the problem is there are a lot of different item types so I will need to have a lot of lines in my CSS file. I was wondering how to apply the background-image: url(images/type1.giff); style to the nested divs without assigning it to each one. eg. I want to change the code for the "itemstable" div so that it applies a css rule to the nested divs.

Is this possible?

EDIT: I'm looking for something like this:

<div id="itemstable" style="SET BACKGROUND IMG FOR NESTED DIVS HERE">
...other divs here...
</div>

Upvotes: 0

Views: 3557

Answers (2)

ndp
ndp

Reputation: 21996

I think including a little more of your HTML would make your question easier to understand.

You can certainly include multiple rules in a compound selector:

.item_type1 div.a, .item_type1 div.b, .item_type1 div.c {
  background-image: url(xyz.gif);
}

But since you are pulling images from the database dynamically, you will need to either include them in your dynamic code-- in the divs themselves, or dynamically create CSS as suggested above:

<style>
<% for $i in $images { echo "div.image$i div { background-image: url(/path/to/$i) }" %>
</style> 

Upvotes: 1

deceze
deceze

Reputation: 522175

(If I'm understanding the question correctly:)

Think about using a different ID/class scheme. I don't know about the further specifics of your structure, but id="itemstable" class="item_type1" seems slightly redundant to me. Can itemstable be anything else than item_type1? Try to apply more generic class names and keep the specific cases for IDs.

Failing that, you can add another class that is responsible for adding the background image: class="item_type1 item_types".

EDIT

Since it seems sheer mass is the main problem (not applying the style as the title suggests) it's probably best to dynamically insert a style in the page header. Something along the lines of:

<head>
    ...
    <style type="text/css" media="screen">
        <?php echo "#$myelement"; ?> div { background: url(<?php echo $image; ?>) ...; }
    </style>
</head>

Inline styles can only apply to the element directly, not one of its children. I.e.:

<div style="background: ...;">

The background only applies to this one div.
You can't use selectors in inline styles like:

<div style="div { background: ...; }">

Upvotes: 1

Related Questions