Skip to main content

伪类与伪元素选择器

链接伪类

  • :link 表示作为超链接,并指向一个未访问的地址的所有锚
  • :visited 表示作为超链接,并指向一个已访问的地址的所有锚
  • :target 代表一个特殊的元素,它的id是URI的片段标识符

注意:link,:visited,:target是作用于链接元素的!

动态伪类

  • :hover 表示悬浮到元素上
  • :active 表示匹配被用户激活的元素(点击按住时)

注意:hover,:active基本可以作用于所有的元素

  • 由于a标签的:link:visited可以覆盖了所有a标签的状态,所以当:link,:visited,:hover,:active同时出现在a标签 身上时, :link和:visited不能放在最后!!!

  • 隐私与:visited选择器,只有下列的属性才能被应用到已访问链接:

    • color
    • background-color
    • border-color

表单相关伪类

  • :enabled 匹配可编辑的表单
  • :disable 匹配被禁用的表单
  • :checked 匹配被选中的表单
  • :focus 匹配获焦的表单

结构性伪类

  • nth-child系列
    • ul > li:nth-child(index) 表示匹配父元素ul中第index的子元素,这个子元素必须是li,
    • :first-child 第一个子元素
    • :last-child 最后一个子元素
    • :nth-last-child(index) 从后开始,倒数第index子元素
    • :only-child 匹配只有一个子元素的情况(等于:first-child:last-child 或者 :nth-child(1):nth-last-child(1))
  • nth-of-type系列
    • #ul > li:nth-of-type(index) 表示匹配父元素ulli的第index个。
    • :first-of-type 第一个子元素
    • :last-of-type 最后一个子元素
    • :nth-last-type(index) 从后开始,倒数第index子元素
    • :only-of-type 匹配只有一个子元素的情况(等于:first-of-type:last-of-type 或者 :nth-of-type(1):nth-last-of-type(1))
  • 区别
    • nth-of-type以元素为中心,比较宽松一点,匹配的第index个子元素,这个子元素可以不存在父元素的index位置
    • nth-child比较严格一点,匹配第index个子元素,并且这个子元素必须在父元素的index位置。
  • index的值范围
    • index的值从1开始计数!!!!
    • index可以为变量n(只能是n)
    • index可以为even odd
  • 其他
    • :not(selector) 匹配所有不符合selector的元素
    • :empty(内容必须是空的,有空格都不行,有attr没关系)

扩展:css3选择器nth-child和nth-of-type之间的差异

伪元素

  • ::after
  • ::before
  • ::firstLetter
  • ::firstLine
  • ::selection