我也不知道该如何描述这个问题。
先上代码吧
这是正常情况下。
*{
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;
}
这个是什么原理,一头雾水,特来请教大佬们。
这是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
所覆盖