CSS3提供了一系列的伪类来对元素进行样式的选择,其中之一便是nth伪类。nth伪类根据元素在一组元素中的位置来进行样式选择,可以选择并改变特定的元素样式。
/* nth伪类的语法如下: */ :nth-child(n) /* 选取第n个元素 */ :nth-last-child(n) /* 选取最后一个元素 */ :nth-of-type(n) /* 选取第n个指定元素 */ :nth-last-of-type(n) /* 选取最后一个指定元素 */ :first-child /* 选取第一个元素 */ :last-child /* 选取最后一个元素 */ :first-of-type /* 选取第一个指定元素 */ :last-of-type /* 选取最后一个指定元素 */ :only-child /* 选取唯一的一个元素 */ :only-of-type /* 选取唯一的指定元素 */
下面来看几个例子:
/* 选中列表中的第二个元素 */ li:nth-child(2) { color: red; } /* 选中列表中的最后一个元素 */ li:nth-last-child(1) { color: blue; } /* 选中段落中的第一个span元素 */ p span:nth-of-type(1) { font-size: 16px; } /* 选中段落中的最后一个span元素 */ p span:nth-last-of-type(1) { font-weight: bold; }
使用nth伪类可以实现更加细致的元素样式选择,使得网页设计更加灵活美观。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did245819