2016-09-23 131 views
0

我一直想弄清楚为什么我的代码不能按预期工作。 基本上我想ups imgwidth: 60px和fedex imgwidth: 100pxCSS最后孩子选择所有?

我的标记是:

<div class="delivery-services"> 
    <span>Delivery Services</span> 
    <br> 
    <a href="#"><img src="img/fedex.png" alt="fedex" /></a> 
    <a href="#"><img src="img/ups.png" alt="ups" /></a> 
</div> 

SCSS是:

.delivery-services { 

    &:nth-child(3) img { 
    width: 100px; 
    } 

    &:last-child img { 
    width: 60px; 
    } 
} 

但现在看来,这两个IMG被last-child影响!

+0

请参阅http://stackoverflow.com/questions/15149641/do-i-need-a-at-the-end-of-an-img-or-br-tag-etc关于关闭'img无关的问题'标签。 – 2016-09-23 04:35:47

+0

谢谢,这是笔http://codepen.io/anon/pen/YGNgkj – Jim

+0

好吧,'delivery-services' **是**父母的最后一个孩子。尝试在'&'之后添加空格。Devtools风格的检查员是你的朋友。 – 2016-09-23 04:53:44

回答

2

这里是一个浏览器如何处理您的选择.delivery-services:last-child img

  1. 查找与类.delivery-services元素,并确保它是最后一个孩子。它发现<div class="delivery-services">,它确实是最后一个孩子。如果你改变了你的HTML有点像这样:

    <div class="delivery-services"> 
        <span>Delivery Services</span> 
        <br> 
        <a href="#"><img src="img/fedex.png" alt="fedex" /></a> 
        <a href="#"><img src="img/ups.png" alt="ups" /></a> 
    </div> 
    <div>I am last child now</div>` 
    

    你会看到你的选择没有任何img元素相匹配。

  2. 查找元素中的所有元素img在第一步

这就是为什么风格width: 60px;适用于所有img元素中找到的。

我还建议你在这些图像上使用类。 nth-child选择器非常适合反复出现的格式,例如,每个第3行都必须具有绿色背景。

这里是修复你的问题,如果你需要使用nth-child选择:

.delivery-services { 

    :nth-child(3) img { 
    width: 100px; 
    } 

    :last-child img { 
    width: 60px; 
    } 
} 
+0

工程谢谢,我在scss所以在我的文件中它应该是'&:nth - ..'(y) – Jim

+0

@Jim,如果答案,你可以接受我的答案你的问题 :)。如果你这样写:&:nth-​​.',这将是你一开始就有的。我的版本应该可以运行。 –

1

现在你有.delivery-services :: nth-child(3),这意味着它适用于作为父项的第三个孩子的.delivery-services元素。这不是你想要的。您正在寻找一个<a>,这是.delivery-services的第三个孩子。所以,你需要你的CSS是:

.delivery-services { 

    & a:nth-child(3) img { 
    width: 100px; 
    } 

    & a:last-child img { 
    width: 60px; 
    } 
} 
1

当使用CSS,你必须要考虑的操作顺序。在你提供的例子中,考虑一下这个层次结构。当应用这种风格时,它将它设置在顶部并减弱。例如,delivery-services - > a - > img。要将其应用于子类,请理解您正在寻找第一个a中的图像。因此,我将其设置类似于:

.delivery-services a:nth-child(4) img{ 
    width: 100px; 
    } 
.delivery-services a:nth-child(3) img{ 
    width: 60px; 
} 

然而,对于像这样的特定情况下,我会分配一个不同的类,每个实例或内嵌样式。 nth-child是循环和迭代的理想选择。

+0

感谢您的解释。我知道对这些选择器有很好的把握。 – Jim