luca
luca

Reputation: 37136

css selector: first paragraph's first letter inside a div

<div>
 <p>
  Once upon a time..
 </p>
 <p>
  A beautiful princess..
 </p>
</div>

How can I select (in my css) the first letter of the first paragraph inside this div??

Thanks

Luca

Upvotes: 13

Views: 22577

Answers (7)

Andrei Duca
Andrei Duca

Reputation: 392

You can directly target the first letter of the entire div:

div:first-letter {
    color: red;
}

demo: https://codepen.io/anon/pen/gRoypa

Upvotes: -1

Demian Brecht
Demian Brecht

Reputation: 21368

div p:first-of-type:first-letter { font-weight: bold; }

Upvotes: 27

Philll_t
Philll_t

Reputation: 4437

In some cases you may have a header or some other elements types before the <p> For example:

<div>    
<h1>My Great Title</h1>
<p>
In my younger years I was a great man, but all that changed when I saw...
</p>
<p>
I struck him for shaming my name, my family, my life. It was a shameful...
</p>
</div>

So in this case, p:first-child won't work for some reason, at least not in Chrome or Safari.

So instead you'll want to use this:

div p:first-of-type:first-letter{
/* add your awesome code here */
}

Thank you for your time.

first-of-type

Upvotes: 8

Dave
Dave

Reputation: 6179

Well, I would add at least a class to the element you want the first-letter styling to be applied to. I'm sure you can do a css rule for the first paragraph of the first div; but if you happen to have another div with a paragraph at the beginning, then it is going to be applied to all of them. In other words, without using a class/id in your selector, it will be applied to the first letter of the first paragraph of EVERY DIV (which might not be the behavior you're looking for). So I would recommend this:

<div>
 <p class="FirstLetter">
  Once upon a time..
 </p>
 <p>
  A beautiful princess..
 </p>
</div>

And then in your css:

.FirstLetter:first-letter {
   // styling rules here
}

But if my intuition is incorrect and you know for sure that this is what you're looking for, then @Demian Brecht's answer should do fine.

Upvotes: 0

ExtraGravy
ExtraGravy

Reputation: 64

CSS :first-letter Selector

div p:first-letter{
 color:blue;   
}

Working example HERE

Note: The following properties can be used with :first-letter

font properties, color properties, background properties, margin properties, padding properties, border properties, text-decoration, vertical-align (only if float is 'none'), text-transform, line-height, float, clear

Upvotes: -1

Kyle Sletten
Kyle Sletten

Reputation: 5413

Yes, it's actually really simple:

div p:first-letter

Upvotes: -1

Ian Pugsley
Ian Pugsley

Reputation: 1062

You can use the CSS :first-letter pseudo-element to apply style to the first letter of a block-level element.

Upvotes: 1

Related Questions