vdh_ant
vdh_ant

Reputation: 13156

CSS3 odd and even only visible rows

I'm trying to stripe the colours of alternating elements. But I want the row colors to alternate only the visible rows. If you have a look at the below here is my attempt at trying to get it working.

http://jsfiddle.net/kuwFp/3/

<!DOCTYPE html>
<html>
<head>
<style>
p:not(.hide):nth-child(odd)
{
background:#ff0000;
}
p:not(.hide):nth-child(even)
{
background:#0000ff;
}
.hide { display:none; }
</style>
</head>
<body>

<p>The first paragraph.</p>
<p class="hide">The second paragraph.</p>
<p>The third paragraph.</p>

</body>
</html>

Upvotes: 8

Views: 4095

Answers (4)

Alan Liang
Alan Liang

Reputation: 1087

Late answer: now we can use the :nth-child(nth of selector) syntax, which, according to MDN, should be supported by most “evergreen” browsers (CR 111, FF 113, Safari 9).

.list div:nth-child(odd of :not([hidden])) { background: ghostwhite; }
[hidden] { display: none; }
<div class="list">
  <div>1</div>
  <div hidden>2</div>
  <div>3</div>
  <div hidden>4</div>
  <div>5</div>
  <div hidden>6</div>
  <div>7</div>
</div>

Upvotes: 0

Eduardo Po&#231;o
Eduardo Po&#231;o

Reputation: 3079

If you have access to the code that hides and shows the elements, you could add another auxiliary hidden element right after each original hidden one, so the parity will be preserved for the css selector. Also, remove each following hidden auxiliary element when the original one is shown up again.

Upvotes: 0

kornieff
kornieff

Reputation: 2557

The trick is to hide a row with different tag, not class. In my example I use "del" tag to hide.

.list div:nth-of-type(odd) { background: ghostwhite; }
.list del { display: none; }
<div class="list">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <del>4</del>
  <div>5</div>
  <del>6</del>
  <div>7</div>
</div>

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

You can't do this with pure CSS because the :nth-child selector is calculated with respect to the element and :not does not filter element position in the DOM. You need to use JavaScript for a fully flexible solution.

It's still possible for you to do this inflexibly by making elements after .hide with :nth-child alternate the color they should be:

.hide + p:nth-child(odd) {
    background: #0000ff;    
}

You can continue to add similar rules for more and more combinations of sibling .hide and p, but this is very inflexible.

Upvotes: 6

Related Questions