0

I have a list of DIVs that share the same classes as follows:

<div class="content1"><div class="contentInner">Text1</div></div>
<div class="content1"><div class="contentInner">Text2</div></div>
<div class="content1"><div class="contentInner">Text3</div></div>
...

I want the first DIV with class="content1" to have a different style than the following DIVs of the same class. What is the CSS selector that can accomplish this? Thanks

potashin
  • 44,205
  • 11
  • 83
  • 107
Gloria
  • 1,305
  • 5
  • 22
  • 57
  • you could add: id="specificdiv1" to the first div. Then in CSS you can use: #specificdiv1 to address it. You can have class and id in same div. – arleitiss Mar 01 '15 at 17:17
  • 1
    possible duplicate of [CSS selector for first element with class](http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class) – David Kiger Mar 01 '15 at 17:19

4 Answers4

1

CSS has a pseudo selector which is used in such scenario where you need to select the first element from similar elements i.e. :first-child

The :first-child CSS pseudo-class represents any element that is the first child element of its parent.

Example:

div.content1:first-child{

  /* your css */
}

Js Fiddle Demo

Sachin
  • 40,216
  • 7
  • 90
  • 102
1

Use nth-of type selector.

.content1:nth-of-type(1){
  /* your style */
}

Using first-child only works if there is no sibling element before your desired div.

See fiddle here.

jp-jee
  • 1,502
  • 3
  • 16
  • 21
0

Use :not and :first-child pseudo selector of CSS to give specific css to the first div.

Example:

.content1:not(:first-child) {
    /* Common CSS for all divs except first div */
}

.content1:first-child {
    /* CSS for first div */
}
Anupam Basak
  • 1,503
  • 11
  • 13
0

you can use the :first-child selector. e.g

.content1:first-child{
text-decoration:underline;
}

fiddle

vbouk
  • 308
  • 2
  • 7