sullivansg sullivansg - 3 months ago 16
CSS Question

First-child bug?

I'm trying to create a Drop Cap using

p:first-child:first-letter
but I'm having a problem. If I apply my styles to the markup below, my drop cap for the first letter in the first paragraph works fine:

<div class="wrapper">
<p>Some paragraph goes here...text text</p> (works good!)
<p>Next paragraph goes here...more text</p>
<p>Next paragraph goes here...more text</p>
</div>


But, if I add an image with a left float before the first paragraph, it breaks. My Drop Cap no longer works for this:

<div class="wrapper">
<img src="some-image.jpg" /> (causes it to break?)
<p>Some paragraph goes here...text text</p> (doesn't work)
<p>Next paragraph goes here...more text</p>
<p>Next paragraph goes here...more text</p>
</div>


Here's my css for the drop cap:

.wrapper p:first-child:first-letter {
float: left;
color: #007ac3;
padding: 4px 5px 0 0;
font: 75px/50px 'Novecento', Arial, serif;
}


So, I'm kind of stumped on why it breaks if I add another element in front of the paragraph. It's not another paragraph so it should work unless there's a rule I'm not aware of. Any ideas?

Answer

To target the first p element, use :first-of-type:

.wrapper p:first-of-type:first-letter {
    float: left;
    color: #007ac3;
    padding: 4px 5px 0 0;
    font: 75px/50px 'Novecento', Arial, serif;
}

:first-child targets the only the very first child. If the element isn't the first child, it will not be selected.