Reputation: 7
I am trying to select a a specific occurrence of a type of element in CSS, to style it.
For example:
<span>Some random stuff</span>
<p>Occurrence 1 of p</p>
<ul>
<li>Random stuff</li>
<li>More random stuff</li>
</ul>
<p>Occourence 2 of p</p>
<span>Even more random stuff</span>
I want to style Occourence 1 and 2 of p in different ways, in external CSS. I know that it would be easier to just use inline CSS, but I need to do it externally. Also, I know I can use an id or class for each occourence of p, but I want to see if I can find a way to do it without that.
Upvotes: 0
Views: 676
Reputation: 431
You could use the :nth-of-type()
selector to choose which one you want to style differently.
p:nth-of-type(1) {
/* Code */
}
p:nth-of-type(2) {
/* Code */
}
I know you said you didn't want to add an id
, but you could use a class
to identify the element.
HTML:
<span>Some random stuff</span>
<p class="first">Occurrence 1 of p</p>
<ul>
<li>Random stuff</li>
<li>More random stuff</li>
</ul>
<p class="second">Occourence 2 of p</p>
<span>Even more random stuff</span>
CSS:
.first {
/* Code */
}
.second {
/* Code */
}
If you only wanted to get the first <p>
you could p:first-of-type
such as:
p:first-of-type {
/* Code */
}
There are many different selector types you can choose from, listed here.
Upvotes: 1
Reputation: 42384
Without adding IDs or classes, it sounds like you're looking for the :nth-of-type CSS pseudo-selector:
p:nth-of-type(2) {
color: red;
}
li:nth-of-type(1) {
color: blue;
}
<span>Some random stuff</span>
<p>Occurrence 1 of p</p>
<ul>
<li>Random stuff</li>
<li>More random stuff</li>
</ul>
<p>Occourence 2 of p</p>
<span>Even more random stuff</span>
Hope this helps! :)
Upvotes: 1