需求:一个table 需要在第一列生成序号:1、2、3、4、5...... 并且自适应行数
不使用后台程序,开始考虑使用JS,但是一旦前台排序后,序号就乱了,
最后采用CSS的一个计数器方法实现!
<!DOCTYPE html> <html> <head> <style>
/*couter-reset:创建或重置一个或多个计数器*/ body {counter-reset:section;} h1 {counter-reset:subsection;}
/*伪元素:before :在每个h1内容之中的第一个之前执行*/ h1:before { counter-increment:section; /* counter-increment:递增一个或多个计数器值*/ content:"Section " counter(section) ". "; /* content 属性与 :before 及 :after 伪元素配合使用,来插入生成内容 */ } h2:before { counter-increment:subsection; content:counter(section) "." counter(subsection) " "; } </style> </head> <body> <p><b>Note:</b> IE8 supports these properties only if a !DOCTYPE is specified.</p> <h1>HTML tutorials</h1> <h2>HTML Tutorial</h2> <h2>XHTML Tutorial</h2> <h2>CSS Tutorial</h2> <h1>Scripting tutorials</h1> <h2>JavaScript</h2> <h2>VBScript</h2> <h1>XML tutorials</h1> <h2>XML</h2> <h2>XSL</h2> </body> </html>
简单介绍上例中使用的属性
1、伪元素:before 选择器,向选定的元素前插入内容。使用 content 属性来指定要插入的内容。
<!DOCTYPE html> <html> <head> <style> p:before { content:"Read this -"; } </style> </head> <body> <p>My name is Donald</p> <p>I live in Ducksburg</p> <p><b>Note:</b> For :before to work in IE8, a DOCTYPE must be declared.</p> </body> </html>
效果:
Read this -My name is Donald
Read this -I live in Ducksburg
Read this -Note: For :before to work in IE8, a DOCTYPE must be declared.
2、:after 选择器向选定的元素之后插入内容。使用 content 属性来指定要插入的内容。
<!DOCTYPE html> <html> <head> <style> p:after { content:"- 注意我"; } </style> </head> <body> <p>我的名字是 Donald</p> <p>我住在 Ducksburg</p> <p><b>注意:</b> :after在IE8中运行,必须声明<!DOCTYPE> </p> </body> </html>
效果:
我的名字是 Donald- 注意我
我住在 Ducksburg- 注意我
注意: :after在IE8中运行,必须声明 - 注意我
3、counter-reset:创建或重置一个或多个计数器,通常是和counter-increment属性,content属性一起使用
4、counter-increment:递增一个或多个计数器值,通常用于counter-reset属性和content属性。
5、content 属性与 :before 及 :after 伪元素配合使用,来插入生成内容。
<!DOCTYPE html> <html> <head> <style> body {counter-reset:section;} h1 {counter-reset:subsection;} h1:before { counter-increment:section; content:"Section " counter(section) ". "; } h2:before { counter-increment:subsection; content:counter(section) "." counter(subsection) " "; } </style> </head> <body> <p><b>Note:</b> IE8 supports these properties only if a !DOCTYPE is specified.</p> <h1>HTML tutorials</h1> <h2>HTML Tutorial</h2> <h2>XHTML Tutorial</h2> <h2>CSS Tutorial</h2> <h1>Scripting tutorials</h1> <h2>JavaScript</h2> <h2>VBScript</h2> <h1>XML tutorials</h1> <h2>XML</h2> <h2>XSL</h2> </body> </html>
效果: