AntG AntG - 1 month ago 4
CSS Question

How to apply in page style to different divs

I need to apply styles dynamically when the page is served and as I am not applying the style directly to the element I use an in-page


However, this will apply the last seen style to all elements on the page. I tried to get around this by uniquely identifying the element, but this seemed to stop the tag from working.

See this fiddle for a simplified version
Both inner boxes are green.

If I try and separate them by using the ID when I attach a # styling to the tag they stop working.

second fiddle here

Using the same ID (third fiddle: works, in that the style tag is applied but has the same problem of attaching the last style in the page to all elements, so it is not using # that is the problem.

Why is this not allowing unique ID references? And no, adding the styling to an external style sheet is not the answer I am looking for.

Ok a bit more information as I can see the answers are focussing on CSS styling that I am already aware of.

The actual behaviour is to allow a div inside a div to 'pop-up' on hover (using CSS only, not javascript), therefore I need to add the style to the parent :hover element. This is why I can't apply a class directly to the affected element.

<div id="1" class="Parent">
<div class="Popup"></div>

The css need to be

.Parent:hover div.Popup { do stuff }

The HTML is being generated by a PHP object. So when that object is called twice on the same page, it produces the scenario described in my first Fiddle.

This all works fine, but it means that the popup amount of all elements on the page needs to be the same. I would like them to be able to be different. Hence I thought to add a (unique) ID to each element and reference that instead. Each time the object is called it can output an in page style unique to the element it is about to create.

Only it doesn't work, second Fiddle.

I don't know why this doesn't work. Is it a quirk of in-page styles, is it in the standard? Or have I got something wrong, is there a fix?


Duplicate style declarations like that are going to end up in having one of them ignored. Also while class declarations can start with a number, you can't do that with IDs. Notice that I changed your outer div IDs from #1 to #outer1 and #2 to #outer2.

<style>#outer1 div.inner{background-color:red}</style>
<div id="outer1" class="outer">
  <div class="inner">
    more content

<style>#outer2 div.inner{background-color:green}</style>
<div id="outer2" class="outer">
  <div class="inner">
    more content