Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 784
caramba Avatar asked Oct 15 '13 13:10

caramba


People also ask

How do you select the first type in CSS?

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

What is P first-of-type?

Definition and Usage The :first-of-type selector matches every element that is the first child, of a particular type, of its parent. Tip: This is the same as :nth-of-type(1).

Is first-of-type A pseudo element?

The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements.

How do I select the first child of a class in CSS?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.


1 Answers

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;
}
like image 79
BoltClock Avatar answered Sep 28 '22 07:09

BoltClock