mheavers mheavers - 4 months ago 16
CSS Question

how to ensure that each time a css class name changes from the previous, it is applied a specific style

I have a table structure shown below, and I want to make sure that each time a switches class from 'odd' to 'even' or from 'even' to 'odd', the s inside the row of the new class get applied a certain style. So in the example, the first 'even' row after the 7 odd rows would have s with a greater top padding than the rest, and then, the first 'odd' row after that (7 rows down) would have greater top padding as well.

I can use either css (preferred) or javascript / jquery to accomplish this. How do I make that happen? Note that I do not have the ability to generate the initial table structure in with any different markup than what is shown below.

enter image description here




Table generating function (only concerned with structure of 'newtable'):

$('.table').each(function() {
var table = $(this); // cache table object
var head = table.find('thead th');
var rows = table.find('tbody tr').clone();
var newtable = $(
'<table class="table mobile">' +
' <tbody>' +
' </tbody>' +
'</table>'
);

// cache tbody where we'll be adding data
var newtable_tbody = newtable.find('tbody');

rows.each(function(i) {
var cols = $(this).find('td');
var classname = i % 2 ? 'even' : 'odd';

cols.each(function(k) {
var new_tr = $('<tr class="' + classname + '"></tr>').appendTo(newtable_tbody);
var headEl = head.clone().get(k);
new_tr.append(headEl);
new_tr.append($(this));
var isEmpty = $(headEl).hasClass('empty'); //check for table columns being used as headers, make sure they span two columns on mobile so that the regular table data isn't as wide as the column header. Note that this assumes mobile `.table`s will only ever be 2 columns
if (isEmpty){
$(this).attr('colspan',2);
}
});
});

$(this).after(newtable);
}

Answer

You can achieve this using CSS' + next sibling selector.

.odd {
  color: red;
}
.even{
  color: blue;
}

tr.odd + tr.even td {
  padding-top: 20px;
}

tr.even + tr.odd td {
  padding-top: 20px;
}
<table>
  <tr class="even">
    <td>Sample Row 01</td>
  </tr>
  <tr class="even">
    <td>Sample Row 02</td>
  </tr>
  <tr class="even">
    <td>Sample Row 03</td>
  </tr>
  <tr class="odd">
    <td>Sample Row 04</td>
  </tr>
  <tr class="odd">
    <td>Sample Row 05</td>
  </tr>
  <tr class="odd">
    <td>Sample Row 06</td>
  </tr>
  <tr class="even">
    <td>Sample Row 07</td>
  </tr>
  <tr class="even">
    <td>Sample Row 08</td>
  </tr>
  <tr class="odd">
    <td>Sample Row 09</td>
  </tr>
  <tr class="even">
    <td>Sample Row 10</td>
  </tr>
</table>