CSS 如何在不使用 javascript 和偶数/奇数类生成的情况下在 html 表上创建斑马条纹?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2765510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:00:21  来源:igfitidea点击:

How to create zebra stripes on html table without using javascript and even/odd classes generation?

csshtml-table

提问by Vladimir

I want to zebra-stripe a html table without using any js stuff or writing server-side code to generate even/odd classes for table rows. Is it ever possible to do using raw css?

我想在不使用任何 js 内容或编写服务器端代码的情况下对 html 表进行斑马条纹化,以生成表行的偶数/奇数类。是否有可能使用原始 css?

回答by K. Norbert

It is possible, with CSS3 selectors:

使用 CSS3 选择器是可能的:

tr:nth-child(even) {
  background-color: red;
}


tr:nth-child(odd) {
  background-color: white;
}

According to caniuse.com, every browser supports it now.

根据caniuse.com,现在每个浏览器都支持它。

回答by ScottE

If all you're changing is the background colour, then the following would work, where test.gif is a 40px high image with the top 20px one colour, and the bottom 20 pixels the other colour. If you need to change any other css properties you're pretty much stuck.

如果你改变的只是背景颜色,那么下面的方法会起作用,其中 test.gif 是一个 40 像素高的图像,顶部 20 像素是一种颜色,底部 20 像素是另一种颜色。如果您需要更改任何其他 css 属性,您就会陷入困境。

table {  background: url(test.gif) top; }
table tr { height: 20px; }

回答by Francisco Aquino

http://www.w3.org/Style/Examples/007/evenoddCSS 3 nth-child. Since browser support is limited you can reproduce the behavior with Sizzle (included in, jquery for example)

http://www.w3.org/Style/Examples/007/evenoddCSS 3 nth-child。由于浏览器支持有限,您可以使用 Sizzle 重现该行为(例如包含在 jquery 中)

回答by icio

(In CSS <= 2) Nope. Unfortunately there aren't any selectors (in CSS <= 2) that operate based on the position (in terms of the number it is within it's parent's children) which I believe you would need to do this with just CSS.

(在 CSS <= 2 中)不。不幸的是,没有任何选择器(在 CSS <= 2 中)基于位置(就它在其父子节点中的数量而言)进行操作,我相信您只需要使用 CSS 即可做到这一点。

Note to self: read up on CSS3, already!

自我注意:已经阅读了 CSS3!

回答by ANeves

In http://www.w3.org/TR/css3-selectors/#structural-pseudosyou can find explanation and examples on using nth-child:

http://www.w3.org/TR/css3-selectors/#structural-pseudos 中,您可以找到有关使用 nth-child 的说明和示例:

tr:nth-child(2n+1) /* represents every odd row of an HTML table */ {
  background-color: green;
}
tr:nth-child(odd)  /* same */ {
  background-color: green;
}
tr:nth-child(2n+0) /* represents every even row of an HTML table */ {
  background-color: pink;
}
tr:nth-child(even) /* same */ {
  background-color: pink;
}

Good luck with browser compatibility- you'll need it.
There are hacks to make it work in IE (using JS) - I'll leave that sifting to you.

祝你浏览器兼容性好- 你会需要它。
有一些技巧可以让它在 IE 中工作(使用 JS) - 我会把筛选留给你。