I am the first box in di...">

CSS: the first type does not work

I thought: first-of-type will affect the first type, which in my case

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

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

But I need <div class="top"> , so why doesn't it work 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; } 
+6
source share
2 answers

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

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

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

The CSS declaration is too qualified. If this design pattern is repeated across the site, then using the following sibling selector is just as good and cleaner:

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

The browser scans the declaration from right to left, so it will check all .box classes and then scan the .box classes that are associated with .top . By adding additional classes, the browser is forced to rescan 2 more times before applying declaration styles.

+1
source

Source: https://habr.com/ru/post/955984/


All Articles