tyialo tyialo - 5 months ago 18
HTML Question

How can I change the background for every second class of a div

I want to for every second div with a specific class col-forum-main-cat an another backgroundcolor. I tried it already with :nth-child(even) and (odd) but it's dont work for me.

The markups is here, and the structure can't be changed, because of the cms..



.col-forum-main-cat:nth-child(odd) {
background:#dedede;
}

<div class="row row-forum-main-head">
<div class="col-xs-12 col-forum-main-cat">
<span>title</span>
</div>
<div class="col-xs-12 col-forum-main-baord">
<strong>text</strong>
</div>
<div class="col-xs-12 col-forum-main-baord">
<strong>text</strong>
</div>
<div class="col-xs-12 col-forum-main-baord">
<strong>text</strong>
</div>
<div class="col-xs-12 col-forum-main-cat">
<span>title</span>
</div>
<div class="col-xs-12 col-forum-main-baord">
<strong>text</strong>
</div>
<div class="col-xs-12 col-forum-main-cat">
<span>title</span>
</div>
<div class="col-xs-12 col-forum-main-cat">
<span>title</span>
</div>
<div class="col-xs-12 col-forum-main-baord">
<strong>text</strong>
</div>
<div class="col-xs-12 col-forum-main-cat">
<span>title</span>
</div>
</div>




Answer

I don't think it's possible with just CSS.

Since you tag this with Jquery you can use this code:

$(document).ready(function(){
  $( ".col-forum-main-cat" ).filter( ":odd" ).css( "background-color", "red" );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row row-forum-main-head">
  <div class="col-xs-12 col-forum-main-cat">
    <span>title</span>
  </div>
  <div class="col-xs-12 col-forum-main-baord">
    <strong>text</strong>
  </div>
  <div class="col-xs-12 col-forum-main-baord">
    <strong>text</strong>
  </div>
  <div class="col-xs-12 col-forum-main-baord">
    <strong>text</strong>
  </div>
  <div class="col-xs-12 col-forum-main-cat">
    <span>title</span>
  </div>
  <div class="col-xs-12 col-forum-main-baord">
    <strong>text</strong>
  </div>
  <div class="col-xs-12 col-forum-main-cat">
    <span>title</span>
  </div>
  <div class="col-xs-12 col-forum-main-cat">
    <span>title</span>
  </div>
  <div class="col-xs-12 col-forum-main-baord">
    <strong>text</strong>
  </div>
  <div class="col-xs-12 col-forum-main-cat">
    <span>title</span>
  </div>
</div>


Note:

You can also just use:

$( ".col-forum-main-cat:odd" ).css( "background-color", "red" );

But I use filter to make it more readable.

Comments