2014-07-17 5 views
0

동일한 반복 div에서 다른 배경색을 사용하고 싶습니다. 예 :동일한 클래스의 CSS, 2 스타일, 각 div 스타일 전환

<div class="test"></div> <!-- this div bg color will be blue --> 
<div class="test"></div> <!-- this div bg color will be red--> 
<div class="test"></div> <!-- this bg div color will be blue --> 
<div class="test"></div> <!-- this bg div color will be red--> 
<div class="test"></div> <!-- this bg div color will be blue --> 
<div class="test"></div> <!-- this bg div color will be red--> 
<div class="test"></div> <!-- this bg div color will be blue --> 
<div class="test"></div> <!-- this bg div color will be red--> 
<div class="test"></div> <!-- this bg div color will be blue --> 
<div class="test"></div> <!-- this bg div color will be red--> 
<!-- and more and more, you got the idea... --> 

나는 각 서버 측 다른 클래스에 인쇄 할 수 있다는 것을 알고,하지만 난 클래스/ID를 추가하지 않고, 그 가능하면 같은 클래스에 CSS에서이 작업을 수행 할 수있는 방법을 찾고 있어요/Js. 감사합니다.

답변

1

다음과 같이 사용할 수 있습니다. nth-child (n) selector.

div.test:nth-child(odd) { 
    background-color: blue; 
} 

div.test:nth-child(even) { 
    background-color: red;  
} 

체크 아웃의 예 IE6, 7, 8이 선택을 지원하지 않는 것으로 여기 http://www.w3schools.com/cssref/sel_nth-child.asp

참고. 선택 |

.test:nth-child(odd) { 
    background: blue; 
} 
.test:nth-child(even) { 
    background: red; 
} 

fiddle

1

두 번째 CSS 클래스를 추가하지 않은 것에 대한 우려가 HTML의 크기, 또는 단순성을 위해서라도, 당신은 그들을 감싸는 컨테이너 요소를 찾을 수있는 한, 'test'클래스를 사용할 필요가 없다.

확인이 바이올린 : http://jsfiddle.net/BuddhiP/aq3uz/

<div class="container"> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 
</div> 

그리고 CSS는에 현장 답변

.container div { 
height: 1em;  
} 


.container div:nth-child(odd) { 
    background: blue; 
    } 
    .container div:nth-child(even) { 
    background: red; 
    }