Div and position

I have five dynamically generated Divs.  In my CSS I have named them .boxes

<style>
.boxes {
width:100px;
height:100px;
float:left;
position:relative;
}
</style>

Open in new window


The first box that is generated I want to have an additional attribute of top:-100px;

How do I apply that to the very first div and not all of the rest?
LVL 7
rgranlundAsked:
Who is Participating?
 
jtwcsCommented:
CSS3 selectors will not work with IE 8 and below.

An alternative would be to use the jQuery first-of-type selector and add the style inline or via a separate class.
0
 
jtwcsCommented:
You could use the first-child selector.

For example,
.boxes:first-child {
    top: -100px;
}

Open in new window

0
 
rgranlundAuthor Commented:
I tried that but it does not seem to work.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
jtwcsCommented:
First-child will only work if that first .boxes div is the first child element of the parent.

You could also try another selector like first-of-type.  This will catch the first .boxes div inside the parent element.
.boxes:first-of-type {
    top: -100px;
}

Open in new window

0
 
rgranlundAuthor Commented:
I tried that and it does not work in IE.
0
 
Ishaan RawatDesigner | Developer | ProgrammerCommented:
See this...

http://selectivizr.com/

It is a good plugin you can add .... Just add the plugin... and then see... your css3 selectors will work.... and your code will run fine...
0
 
Mark BradyPrincipal Data EngineerCommented:
or you could just add it via javascript when you are generating them dynamically. Put a counter in the loop and if it is 1 then add the top margin.
0
 
Chris StanyonCommented:
Whenever I'm generating elements dynamically like this, it can often be useful to add some classes to help with the styling, such as first/last or odd/even:

<div class="boxes first odd">A nicely styled box!</div>
<div class="boxes even">A nicely styled box!</div>
<div class="boxes odd">A nicely styled box!</div>
<div class="boxes even">A nicely styled box!</div>
<div class="boxes last odd">A nicely styled box!</div>

<style>
.boxes { width:100px; height:100px; float:left; position:relative; }
.boxes.first { top: -100px; }
.boxes.last { margin-right: 20px; }
.boxes.odd { background-color: green; } 
.boxes.even { background-color: red; } 
</style>

Open in new window

Simple and works in all browsers - happy days :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.