Reputation: 9587
I try to create styles with first-child and last-child items but I encountered a problem.
When I use first-child, because there is strong item just before, the style isn't apply. But my last-child work fine.
HTML:
<br />
<h2 class="title_block">Info <strong>1</strong>
<span class="title_block_info">+2</span>
<span class="title_block_info">+1</span>
</h2>
CSS:
h2 .title_block_info,
h2 strong {
border: 1px solid #000;
}
h2 .title_block_info:first-child {
border-radius: 10px 0 0 10px;
}
h2 .title_block_info:last-child {
border-radius: 0 10px 10px 0;
}
Example here : http://jsfiddle.net/mYKRW/
Anyone know why this came about?
Thanks,
Upvotes: 1
Views: 1194
Reputation: 253308
The :first-child
pseudo-class selects the first matching element from the selector .title_block_info
if it's also the :first-child
of the parent element; as you note this doesn't work because there's another element that's the first-child of the parent element.
In your case you could either remove the strong
element that's taking the :first-child
position in the DOM, or you could use, instead, the :first-of-type
pseudo-class:
h2 .title_block_info:first-of-type {
border-radius: 10px 0 0 10px;
}
If your HTML is going to remain similarly predictable (the .title_block_info
element will always follow the :first-child
element) you could, instead:
h2 :first-child + .title_block_info {
border-radius: 10px 0 0 10px;
}
References:
Upvotes: 2
Reputation: 47377
It's because you have a "strong" tag as the first child, not the title_block_info
class you were going for. first-child
only works if it is in fact the first child of an element.
This works
<h2 class="title_block">
<span class="title_block_info">+2</span>
<span class="title_block_info">+1</span>
</h2>
If you need that strong text in there, you could try this, notice how I wrapped your two span tages in another span tag. This will allow you to use first-child and last-child
h2 .title_block_info,
h2 strong {
border: 1px solid #000;
}
h2 span .title_block_info:first-child {
border-radius: 10px 0 0 10px;
}
h2 span .title_block_info:last-child {
border-radius: 0 10px 10px 0;
}
<h2 class="title_block">
Info <strong>1</strong>
<span>
<span class="title_block_info">+2</span>
<span class="title_block_info">+1</span>
</span>
</h2>
Lastly you could use the first-of-type
pseudo class if you want to keep your html exactly as you want, and just change your css.
h2 .title_block_info,
h2 strong {
border: 1px solid #000;
}
h2 .title_block_info:first-of-type {
border-radius: 10px 0 0 10px;
}
h2 .title_block_info:last-of-type {
border-radius: 0 10px 10px 0;
}
Upvotes: 3