Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div odd and even

Tags:

html

css

I have a problem that i believe to have a simple fix I just don't know the fix myself.

Say i have some divs i.e.

<div class="box-1"></div>
<div class="box-2"></div>
<div class="box-3"></div>
<div class="box-4"></div>

etc.

If these boxes need to be alternate colours. I need to create some css which basically does the following:

.box-(odd-number) {
    color:#000;
}
.box-(even-number) {
    color:#fff;
}

Obviously I know the above is not the correct syntax. Could some one point me in the right direction.

Thanks

like image 969
user2125467 Avatar asked Jan 22 '16 10:01

user2125467


People also ask

What exactly is div?

The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!


1 Answers

You can use the nth-of-type pseudo-class, combined with the keywords odd and even:

.box:nth-of-type(odd) {
background-color:#000;
}
    
.box:nth-of-type(even) {
background-color:#fff;
}

.box {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid #f00;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
like image 111
Rounin - Glory to UKRAINE Avatar answered Sep 22 '22 01:09

Rounin - Glory to UKRAINE