鍍金池/ 問(wèn)答/HTML5  HTML/ nth-child()選擇器哪里出錯(cuò)?

nth-child()選擇器哪里出錯(cuò)?

我也不知道該如何描述這個(gè)問(wèn)題。
先上代碼吧
這是正常情況下。

*{
            margin: 0;
            padding: 0;
        }
        div{
            margin: 0 auto;
            width: 600px;
            height: 400px;
            background: #abcdef;
        }
        div > .oUl >li{
            list-style: none;
            width:150px;
            height:400px;
            background: url(../images/5.jpg);
            background-repeat: no-repeat;
            float: left;
        }
        .oUl li:nth-child(1){
            background-position: 0 0 ;
        }
        .oUl li:nth-child(2){
            background-position: -150px 0 ;
        }
        .oUl li:nth-child(3){
            background-position: -300px 0 ;
        }
        .oUl li:nth-child(4){
            background-position: -450px 0 ;
        }
  
<div>
        <ul class="oUl">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
    </div>

圖片描述

但是當(dāng)我三個(gè)li:nth-child之前的 .oUl去掉之后,問(wèn)題就來(lái)了。

 .oUl li:nth-child(1){
        background-position: 0 0 ;
    }
    .oUl li:nth-child(2){
        background-position: -150px 0 ;
    }
     li:nth-child(3){
        background-position: -300px 0 ;
    }
    .oUl li:nth-child(4){
        background-position: -450px 0 ;
    }

圖片描述

但當(dāng)給第三個(gè)li添加上margin時(shí),它的margin值卻依然有效。

 li:nth-child(3){
    background-position: -300px 0 ;
    margin-top: 30px;
}

圖片描述

這個(gè)是什么原理,一頭霧水,特來(lái)請(qǐng)教大佬們。

回答
編輯回答
獨(dú)特范

這是CSS優(yōu)先級(jí)問(wèn)題
首先需要明白CSS的background其實(shí)是一種省略的寫(xiě)法,參見(jiàn)https://www.w3schools.com/css...
由于
div > .oUl >li的優(yōu)先級(jí)比li:nth-child(3)優(yōu)先級(jí)要高
因此li:nth-child(3)中定義的background-position其實(shí)會(huì)被div > .oUl >li中的background所覆蓋

2018年3月9日 18:29