2014-09-18 7 views
0

CSS를 통해 요소에 액세스하려는 중 멈추고 이유를 이해하지 못합니다.왜 형제와 : first-child를 이질적인 요소 목록에서 사용할 수 없습니까?

<div class="sample"> 
    <label></label> 
    <div class="ui-random-foo"></div> 
    <label></label> 
    <div class="ui-random-bar"></div> 
    <label></label> 
    <div class="ui-random-baz"></div> 
</div> 

내가 얻을 것이다 얼마나 많은 요소의 페어 알고 요소의 수에 따라 폭을 설정하고 싶어하지 않습니다

는이 같은 <label><div> 조합의 임의의 숫자를 가지고있다.

.sample label ~ div 

작품 반환 위의 예에서 세 <div>, 일 :하지만 내 선택하면서

.sample label ~ div:first-child 

이 작동하지 않습니다.

질문
왜 첫 어린이를 사용할 수 없나요? 내 형제 선택기가 div 요소 그룹을 반환하기를 원했기 때문에 동질 요소에 대해 첫 번째 자식을 사용하고 있습니까? 아니면 또 다른 문제가 있습니까?

+3

[first-child] (https://developer.mozilla.org/en/docs/Web/CSS/:first-child)는 부모의 첫 번째 자식 요소 만 선택합니다. – Pete

+1

': first-child'는 첫 번째 자식 div가 아닌 첫 번째 자식 div – Huangism

+0

@Huangism : 좋은 점 – frequent

답변

0

가 좋아, 최고의 내 필요에 맞는 다른 해결책을 발견 : 그래서

.sample :first-child:nth-last-child(2) ~ div { 
    width: 60%; 
} 
.sample :first-child:nth-last-child(4) ~ div { 
    width: 30%; 
} 
.sample :first-child:nth-last-child(6) ~ div { 
    width: 20%; 
} 
.sample :first-child:nth-last-child(8) ~ div { 
    width: 15%; 
} 

난 아무것도 필터링 아니에요을, 난 항상 쌍있을 것입니다 알고 있기 때문에 그래서 2,4,6,8 요소를 확인하고 각각 형제 div의 너비를 설정합니다. 일하는 것 같습니다. 아이디어에 감사드립니다.

3

당신은 사용할 수 있습니다

.sample div:first-of-type 

첫 번째 DIV를 선택합니다.

예 :

.sample *{ 
 
    height:10px; 
 
    display:block; 
 
    margin-top:5px; 
 
    background:teal; 
 
} 
 
.sample div:first-of-type{ 
 
    background:gold; 
 
}
<div class="sample"> 
 
    <label></label> 
 
    <div class="ui-random-foo"></div> 
 
    <label></label> 
 
    <div class="ui-random-bar"></div> 
 
    <label></label> 
 
    <div class="ui-random-baz"></div> 
 
</div>

+1

좋은 아이디어. 견딜 수 없는. 새로운 snippety 물건을 주셔서 감사합니다 – frequent

4

첫 번째 아이는 레이블 요소입니다. 첫 번째 div는 두 번째 자식입니다.

당신은 사용할 수 있습니다

.sample label:first-child + div 
+0

좋은 생각. 나는 :-)을 좋아한다. – frequent