Ionică Bizău
Ionică Bizău

Reputation: 113385

Select the first CSS element using a pseudo class

I have the following structure:

<div class="myClass">1</div>
<div class="myClass">2</div>

How can I select the first element matched by .myClass?

I know that I can do: [PARENT OF .myClass] .myClass:first-child {/* rules */} but I am curious if there is a pseudo CSS class that selects the first element matched by the selector.

Is that possible? How?

The jQuery selector would look like this: .myClass:first, but :first seems not to work in CSS.

Upvotes: 1

Views: 176

Answers (3)

Alessandro Incarnati
Alessandro Incarnati

Reputation: 7246

You could use:

.myClass:first-of-type {
      background-color:#233423;
      color:#FFFFFF;
    }

http://jsfiddle.net/65adr/44/

or you can give a look here for other alternatives:

http://reference.sitepoint.com/css/css3psuedoclasses

Upvotes: 1

Ale
Ale

Reputation: 2023

Okay, I'm not sure, but this might work for you.

some.great-selector:first-of-type {
  /* Your rules here */
}

This will match only first child that matches some.great-selector in each parent node. This is somewhat different from what :first does in JQuery, but might be still useful, e.g. in conjunction with parent > selector.

Upvotes: 1

Jeffpowrs
Jeffpowrs

Reputation: 4540

:first-child is the closest you will get. Though it is well supported if you're looking for something that will work in legacy browsers.

If you want to achieve support in legacy browsers you can apply a style to all elements with a particular class name and then remove it for all sibling classes as so:

.my-class {
  border-top: 1px solid lightgray;
  border-bottom: 1px solid lightgray;
}

.my-class + .my-class {
  border-top: none;
}

A rather arbitrary example but you'll get the point.

Upvotes: 0

Related Questions