views:

97

answers:

2

While practicing different scenarios in which CSS3 pseudo-classes and selectors might come in handy, I ran across something I just can't figure out!

Here's the situation. I want to modify the :first-of-type::first-letter of the first non-empty paragraph for a block of text. I'm not sure that pseudo-classes can be stacked though. Here's what I've come up with (Doesn't work, of course)

.article-body > p:not(:empty):first-of-type::first-letter { ... }

Given the following markup:

<div class="article-body">
    <p></p>
    <p>The "T" in this paragraph should be the one effected.</p>
</div>

The only guess I can come up with is that pseudo-classes (ie; :not() and :first-of-type) can not be stacked upon each other. Which is odd since you can stack pseudo-elements upon each other, and other pseudo-classes...

Any ideas for how this can be accomplished?!

+1  A: 

:first-of-type selects the first p, as the name suggests, not the first non-empty p as you might want.

They stack just fine, but :first-of-type purely operates on the tag (i.e. type), not on the preceding complex selector. So you just end up looking for the first p, and that first paragraph also shouldn't be empty. And that doesn't exist.

Assuming empty paragraphs might appear throughout the text, and you only want the first, non-empty paragraph to be affected, I don't think it's possible to do this with just one selector. This is the best I can come up with:

p:first-of-type::first-letter,
p:empty + p::first-letter { text-transform: uppercase; /* ... */ }

p:not(:empty) ~ p::first-letter { text-transform: inherit; /* reset */ }

That will apply the CSS only to the first non-empty paragraph (well, and to a first empty paragraph, but it won't do anything then anyway).

mercator
Which is the conclusion I've come to as well. Any idea how to accomplish the same thing without using :first-of-type or :first-child, etc?
Dustin Hansen
Hmmm, and I take it you might have any number of empty paragraphs anywhere in the text? Or is it just the one empty starting paragraph that might or might not be there?
mercator
I updated my answer.
mercator
Very interesting solution! I never even thought to check if the previous sibling was both the first-of-type and empty, then to modify the next sibling if so, ingenious!
Dustin Hansen
A: 

Removing the empty paragraph causes

.article-body > p:first-of-type::first-letter { ... }

to behave properly. Is there any reason that the empty paragraph needs to be there? Can you alter the spacing of the first paragraph to account for the empty one not being there?

Jason Aller
My main concern was for some of the HTML WYSIWYG editors that do not clean up after themselves as far as removing un-used empty p tags. They can of course be programmatically cleaned up, but cannot be guaranteed-- in all cases --that this will be done.
Dustin Hansen