Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 712
vdh_ant Avatar asked Feb 25 '13 02:02

vdh_ant


People also ask

Which CSS would correctly apply the background color to every odd row in your table?

Tap into the tr (table row) element is CSS. Use the nth-child() selector and add background-color of your choice to all odd (or even) table rows.

How do you select all the odd rows in an HTML table?

Use “tr: odd” to select the odd data & use “tr: even” to select the even data in the row.


2 Answers

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.

like image 136
Explosion Pills Avatar answered Sep 29 '22 09:09

Explosion Pills


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>
like image 40
kornieff Avatar answered Sep 29 '22 10:09

kornieff