과거 과도기에 HTML의 멋부림(?)을 위해 Javascript를 사용했던 각종 코드들을 CSS3의 막강한 기능을 이용하면 별도 코드 없이 다이나믹한 화면을 구성할 수 있다.
특히나 특정 객체를 지정하는 CSS3의 Selector 는 매우 유용하다.
예를 들어 반복되는 객체의 세 번째의 스타일을 변경하고 싶다고 하면,
1 2 3 4 5 6 7 8 |
<div class="tab-content"> <ul class="list"> <li>first</li> <li>second</li> <li>third</li> <li>fourth</li> </ul> ... |
1 2 3 |
UL.list LI:nth-child(3) { font-weight: bold; } |
라고 하면 된다.
하지만, 실제로 HTML 문서를 코딩하다 보면 다양한 태그들이 곂쳐서 사용되고, nth-child 의 결과가 의도하지 않게 나오는 경우가 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<div class="tab-content"> <div id="basicinfo" class="tab-pane in active"> <h3 class="header">Basic Information</h3> <form method="post"> <input name="productcode" type="hidden" value="" /> <input name="mode" type="hidden" value="" /> </form> </div> <div id="oqcspecs" class="tab-pane"> <form method="post"> <input name="productcode" type="hidden" value="" /> <input name="mode" type="hidden" value="" /> <h3 class="header">Specifications</h3> <div>...</div> <h3 class="header">Description1</h3> <div>....</div> <h3 class="header">Description2</h3> <div>...</div> <h3 class="header">Test Result</h3> <div>...</div> <h3 class="header">EEPROM Info</h3> <div>...</div> </form> </div> <div id="agreements" class="tab-pane"> <h3 class="header">Agreements</h3> ... </div> <div id="history" class="tab-pane"> <h3 class="header">Comments</h3> .... </div> </div> |
위의 예문은 DIV.tab-pane 내에 H3.header 가 각각 존재하지만, DIV의 padding 이 들어가 있는 관계로 첫 번째 header는 margin-top을 주지 않으려 한다. 직관적으로 :first-chlid를 사용하면 될 것 같다.
:first-child 는 :nth-child(1) 과 같으며 맨 처음 객체를 가져온다. :last-child 는 마지막 객체를 의미한다.
물론 예제에서 FORM 태그의 위치가 각 DIV.tab-pane 마다 다르게 설정된 것은 의도한(!) 실수이다.
1 2 3 4 5 6 7 |
.tab-pane H3.header { margin-top: 10px; margin-bottom: 5px; } .tab-pane H3.header:first-child { margin-top: 0px; } |
이렇게 하면 Basic Information, Agreements, Comments 값을 가지는 H3.header는 :first-child 조건에 맞지만 Specifacition 값을 가지는 H3.header는 해당 스타일이 적용되지 않는다.
이유는, .tab-pane 하위로 오는 태그 중, H3 태그이면서 first-child 여야 하기 때문이다.
예제에서는 Specification 값을 가지는 H3.header 가 FORM 태그 이 후에 위치해서 :first-child 가 되지 않는다.
이 부분을 애초에 의도했던 대로 사용하려면 :first-child 대신 :first-of-type 을 써야한다.
1 2 3 4 5 6 7 |
.tab-pane H3.header { margin-top: 10px; margin-bottom: 5px; } .tab-pane H3.header:first-of-type { margin-top: 0px; } |
의도한 대로 객체 앞에 다른 객체가 있다 하더라도, 해당 type (H3) 중 첫번째 것을 참조한다.
댓글 남기기