0

I am trying to make a table that is striped like : enter image description here

I tried the following :

.competence{
    display: grid;
    grid-template-columns: 33% 40% repeat(9,3%);
    grid-template-rows: auto;
}

.competence-name{
    background-color: #002664;
    color : white;
    grid-column-start: 1;
    grid-column-end: 2;
}

.skills_in_competence{
    grid-column-start: 2;
    grid-column-end: 12;
}

.skill{
    border: 1px solid gray;
    position: relative;
}

.skill:nth-child(2n){
    background-color: red;
}
    <div class="competence">
      <div class="competence-name">
          Competence name
      </div>

      <div class="skills_in_competence">
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
      </div>

    </div>
    <div class="competence">
      <div class="competence-name">
          Competence name
      </div>

      <div class="skills_in_competence">
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
        <div class="skill">
          skill goes here
        </div>
      </div>

The sample above changes the color evenly by skills_in_competence and i would like to have this result globally.

The reason i chose a grid template instead of a table is because i want to have each competence with the respective skills in a wrapper.

What should i do so that i get an evenly striped table ?

Ignacio Ambía
  • 479
  • 5
  • 16

1 Answers1

1

The problem is .skill:nth-child(2n) is using the parent .competence to determine the nth

What you want to do is go "every other" regardless of the parent div.

There isn't really a CSS way to ignore the parent element of the DOM that I'm aware of. And the internet seems to agree. 1 2

So your options are:

  1. Restructure your view so ALL .skills are under a single parent (you could probably still do this with grid-column, but you'd need to re-think your flow quite a bit and nothing obvious is coming to me).

  2. Don't use CSS, instead, after the page loads use javascript to style the rows. For example, jQuery can grab all the matching elements from top to bottom and iterate over them with an index.

Here's what it would look like in jQuery:

$('.skill').each(function(index) {
  if (index % 2 == 0) {
    // Even numbered div
    $(this).addClass('shaded');
  };
};
Chiperific
  • 4,428
  • 3
  • 21
  • 41