0

How to select only for the first of many divs with equal names with CSS? For example i have this:

<div class="div">dsdas</div>
<div class="div">123</div>
<div class="div">73</div>
<div class="div">63</div>
<div class="div">53</div>
<div class="div">45</div>

How to select only the first div(with class "div")?

jcrs
  • 449
  • 4
  • 11

3 Answers3

1

Use the pseudo-selector :nth-of-type(). To select the first element with the class "div", do it like this:

.div:nth-of-type(1) {

}

Working DEMO

Johan
  • 1,016
  • 7
  • 13
  • Thanks that it. It should be like this .div:nth-of-type(1){ margin-left:0px; } – user3442381 Apr 01 '14 at 11:11
  • That will select the first div, not the first div that is a member of a particular class. – Quentin Apr 01 '14 at 11:12
  • Re edit: `:nth-of-type` always selects based on **type**, it doesn't select the first thing that matches the previous part of the selector. – Quentin Apr 01 '14 at 11:14
  • @Quentin You're right this will only work with type, a workaround for use with class can be found [here](http://stackoverflow.com/questions/6447045/css3-selector-first-of-type-with-class-name/6447072#6447072) – Johan Apr 01 '14 at 11:22
0

Use this

.div:nth-of-type(1)
{
    //add style here
} 

Check this fiddle

James
  • 4,540
  • 1
  • 18
  • 34
  • That will select the first div if it is a member of the class, not the first div that is a member of a particular class. – Quentin Apr 01 '14 at 11:15
-1

using jquery :

var firstDiv = $('.div').first();

Documentation http://api.jquery.com/first/

or like this:

var firstDiv = $('.div:first');

http://api.jquery.com/first-selector/

user2167382
  • 346
  • 1
  • 3
  • 14