nth-child()选择器哪里出错?

我也不知道该如何描述这个问题。
先上代码吧
这是正常情况下。

*{
            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>

图片描述

但是当我三个li:nth-child之前的 .oUl去掉之后,问题就来了。

 .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 ;
    }

图片描述

但当给第三个li添加上margin时,它的margin值却依然有效。

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

图片描述

这个是什么原理,一头雾水,特来请教大佬们。

阅读 2.3k
1 个回答

这是CSS优先级问题
首先需要明白CSS的background其实是一种省略的写法,参见https://www.w3schools.com/css...
由于
div > .oUl >li的优先级比li:nth-child(3)优先级要高
因此li:nth-child(3)中定义的background-position其实会被div > .oUl >li中的background所覆盖

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题