caramba
caramba

Reputation: 22480

CSS :first-of-type not working

I thought :first-of-type will effect the first-of-type which in my case is

<div class="box">I am the first box in div.center...</div>

If I remove the <div class="top"> the CSS works and adds the green-top-border.

But I need <div class="top">, so why is it not working if <div class="top"> is there?

FIDDLE

<div class="main-wrap">
    <div class="center">
        <h3>Lorem Ipsum</h3>
        <div class="top">XXX XXX XXXX</div>
        <div class="box">I am the first box in div.center. Why no top border?</div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
    </div>
</div>

.box {
    width:100%;
    height:30px;
    margin:10px 0;
    background-color:orange;
}

.main-wrap .center div.box:first-of-type {
    border-top:4px solid green;
}
.box {
    position:relative;
    border-bottom:4px solid green;
}

Upvotes: 9

Views: 6886

Answers (2)

Roralee
Roralee

Reputation: 548

The CSS declaration is over-qualified. If this design pattern repeats through out the site then using the following sibling selector is just as good and cleaner:

.top + .box {
    border-top: 4px solid green;
}

The browser looks at the declaration from right to left, so will scan for all the .box classes and then scan for the .box classes that are associated .top. By adding the additional classes, the browser is forced to re-scan 2 more times before applying the declaration styles.

Upvotes: 2

BoltClock
BoltClock

Reputation: 723508

When you have div.top there, that becomes the first div element within its parent. :first-of-type only looks at the type of element; div.box:first-of-type really means select div:first-of-type only when it has the class .box, and not the first div.box.

To reach the first div.box, use an adjacent sibling selector:

.main-wrap .center div.top + div.box {
    border-top:4px solid green;
}

Upvotes: 13

Related Questions