2016-09-23 132 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