I want to know is there any way to get the following example of CSS to work as I intend it to?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.col p:first-child {
background:yellow;
}
</style>
</head>
<body>
<div class="col">
<h1>Woot</h1>
<p>I am a super nun. I am a super nun.</p>
<p>I am a super nun. I am a super nun.</p>
</div>
</body>
</html>
Basically I need the first <p>
of an element to be styled a certain way... but first-child
doesn't work if it's the second child (duh), even if I attemp开发者_开发问答t to say: "the first <p>
element in a parent (i.e. .col p:first-child
)".
Is it possible to select not the first-child, but the first-child of a specific type in CSS?
Fortunately, for element types, CSS3 supplies the :first-of-type
pseudo-class (there is no first of class, first of pseudo-class, first with a certain attribute, etc).
.col > p:first-of-type
Unfortunately, since it's a CSS3 selector, browser support for it is pretty poor. Of all IE versions, only IE9 supports it.
If the structure of .col
is predictable (enough) in that, for example, it always contains one element followed by a p
, you could do something like this instead, with just CSS2 selectors:
.col > :first-child + p
That would be the :first-of-type
pseudo-class.
The
:first-of-type
pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.
Now I just need to see how well it's supported.
Here's the quirksmode compatibility table you're looking for. The short version: forget about IE <9.
精彩评论