Style using nth-child to keep table's aspect (

2019-02-05 09:15发布

问题:

I have a CSS table like this:

(this is a reliable simplification of my system)

<div class="table">
    <div class="row">
        <div class="data">
        abc
        </div>
    </div>
    <div class="row">
        <div class="data">
        def
        </div>
    </div>
    <div class="row">
        <div class="data">
        ghi
        </div>
    </div>
    <div class="row">
        <div class="data">
        jkl
        </div>
    </div>
</div>

And I have a CSS like this:

div.table div.row:not(.hide):nth-child(2n){
    background-color: #D7D4DA;
}
div.table div.row:not(.hide):nth-child(2n+1){
    background-color: #E4E8EB;
}

.hide{
    display:none;
}

The purpose is: When a line is hidden (using the class hide), the styling of the table should remain the same (each line with a different color between the two available). Instead, it get's broken.

According to firefox's firebug, the :nth-child is applied before the :not, not after (as I wanted). How can that be solved?

Note: Altering the HTML is a no go. This is something dynamically made using javascript.

My purpose is not to count for the nth-child the lines that are hidden in order to maintain the styling even if the line isn't visible

回答1:

Pure CSS Answer (CSS3)

There are some careful considerations to take into account (see below), but there does appear to be a way to do this in pure css (note that fiddle uses the fake div table per this post, but it could be done with real html tables) using a linear-gradient with color stops (technique found here) on the table background. The key to make it flexible with font-size changes (or zooming) is to set the height portion of the background-size to twice the line-height set for the rows.

Considerations:

  1. line-height and font-size for row should be explicitly set with em units (except see note #5 below).
  2. If padding is set on the table (not recommended) then some type of adjustment to either background-position or background-clip will likely need to be done to accommodate the padding.
  3. If top or bottom padding or margin is set on the row then it should be in em units and added to the line-height value before calculating the doubled linear-gradient height.
  4. This technique will change color of background within a row if that row has multiple lines in it (see the last table in my example fiddle).
  5. If some other fixed height element were in the rows (images set to 20px high), then the row height and linear-gradient height could be set based off pixel values.

I have not taken the time to play around with #2 and #3 above to figure out for sure the exact adjustments needed, but theoretically it should be possible to accommodate those things if necessary.