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;
}
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.
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).
The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements.
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With