Reputation: 6696
I have some section with three children (one <h1>
and two <div>
)
<section class="half">
<h1>Half</h1>
<div>
left half
</div>
<div>
right half
</div>
</section>
Then I am adding some styles to these blocks
section > h1 { ... }
section > div { ... }
I want to specify additional styles for the first <div>
element in the section.
I can't write use just section > :first-child
because first child in section is <h1>
.
So how I should write?
Upvotes: 2
Views: 131
Reputation: 219920
That's what :nth-of-type
is for:
section > div:nth-of-type(1) {
/* CSS properties go here... */
}
Upvotes: 4
Reputation: 157304
Using only section > div:nth-of-type(1) {
will select first div
element where parent element is section
, and hence I feel will be a loose selector, make it stricter by using
section.half > div:nth-of-type(1) { /* This will select 1st div element inside
* section having class .half
*/
/* Styles goes here */
}
You can also use first-of-type
Demo
section.half > div:first-of-type {
/* Styles goes here */
}
Upvotes: 1
Reputation:
No doubt, Joseph Silber answer is great. But if you don't want to use CSS3, here is the trick:
section > div { background: red; }
section > div + div { background: transparent; }
First, you select all div elements and set your properties to it. Then, you select second div and later and reset those properties for it.
Upvotes: 1