Michiel
Michiel

Reputation: 8103

:first-child with different class names

I have a HTML structure:

<div class="home-view">
     <div class="view-header">Header</div>
     <div class="view-content">Content</div>
</div>

And I would like to style the first item of home-view. In this case, it's view-header, but sometimes there is no header and the view-content will be the first item in home-view.

The first item in home-view should get some styles.

I've been trying with .home-view:first-child, but no luck there since it's children have different class-names (I think). Any advice?

Upvotes: 2

Views: 130

Answers (5)

Arun EB
Arun EB

Reputation: 43

.home-view > div:first-of-type{ background-color:red; }

The :first-of-type selector matches every element that is the first child, of a particular type, of its parent.

More....

Upvotes: 1

Spudley
Spudley

Reputation: 168803

You responded to the previous answers that you only wanted the direct child elements to be styled, and not child elements below them.

So I'll adapt those answers and give you an answer that meets that requirement:

.home-view>div:first-child{
    background: red;
}

The difference here is the > selector between .home-view and div instead of a space. This forces it to only select immediate children of .home-view, and not divs that are further down the tree, whereas a space between them would tell it to select any matching child elements down the tree.

Hope that helps.

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 181037

.home-view > *:first-child { background-color:red; }

...will select the first sub element of any type that is a first child.

Upvotes: 4

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Since both elements are divs you could specify the first div within .home-view

.home-view div:first-child{
    background: red;
}

Working Example: http://jsfiddle.net/7cNZS/

Upvotes: 2

Rutwick Gangurde
Rutwick Gangurde

Reputation: 4912

Try this:

$('.home-view').children().eq(0);

Upvotes: -3

Related Questions