flasshy
flasshy

Reputation: 121

Is there a way to select a specific element with a class?

I have a need to apply a specific style only to a specific instance of the class.

So...let's say I have the following in my html:

<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>

Is there a selector or something I can use to apply a slight variation to the second div with the "dog" class but not the other two divs?

Thanks in advance!

Upvotes: 2

Views: 63

Answers (4)

Hiyapiwi
Hiyapiwi

Reputation: 53

If you give one element an id and then specify it in your style sheet it should work.

<div class="dog" id="altered"/>

Upvotes: 1

Weafs.py
Weafs.py

Reputation: 22992

You could use :nth-child() selector.

.dog:nth-child(2) {
  color: red;
}
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>


If you want to select all divs with class .dog, but first and last divs you could combine :not(), :first-of-type and :last-of-type selectors(.dog:not(:first-of-type):not(:last-of-type)).

.dog:not(:first-of-type):not(:last-of-type) {
  color: red;
}
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>
<div class="dog">Text</div>
<div class="dog">More text</div>
<div class="dog">Even more text</div>

Upvotes: 4

greenfox
greenfox

Reputation: 198

you may use eq selector from jQuery: http://api.jquery.com/eq-selector/

If you want to avoid jQuery and javascript you may take a look into :nth-child() pseudo-selector, but is CSS3, and CSS3 is not supported in old browsers.

Upvotes: 1

lazy panda
lazy panda

Reputation: 156

add a second class like this <div class="dog second">More text</div> your css is for example div.dog.second {color:red;}

Upvotes: 1

Related Questions