开发者

How do I style the background color of alternating table rows?

开发者 https://www.devze.com 2023-02-06 04:36 出处:网络
I was was just wondering how to get this kind of design done when things are fetched dynamically? I mean there has to be only one class which can be used to get the background colour depending upon wh

I was was just wondering how to get this kind of design done when things are fetched dynamically? I mean there has to be only one class which can be used to get the background colour depending upon whether block is odd or even. I hope my requirements are clear: background color varying with the odd or even number for the rows.

开发者_高级运维

How do I style the background color of alternating table rows?


You're looking for alternating rows. This is accomplishable by adding a different class to every other row.

Tutorials are plenty on how to do this.

CSS3 also provides a new way to do this without adding classes:

tr:nth-child(odd)   { background-color:#eee; }
tr:nth-child(even)    { background-color:#fff; }


As you've not specified a language for what's returning the code I'll give you a pure CSS answer.

tr:nth-child(2n+1) {YOURSTYLEINHERE}
or
tr:nth-child(odd) {YOURSTYLEINHERE} 


Add a second css class for the alternating row. Assuming that the default bg color here is dark gray, the second class would look like this:

.altRow { background-color:white !important; }

If you don't want to have to code the logic server-side for applying the second class, you can use JQuery's Odd selector. But that's about as close are you're going to get to zebra-striping without just manually applying a second class.


What you want is modulus division

if(rowNum % 2 == 0) {class="even"} else {class="odd"}

OR if you are using CSS3 you can do it like this

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号