css选择器相关(三)--- 伪类与伪元素

伪类

状态伪类

  • :link 应用于未被访问过的链接;
  • :hover 应用于鼠标悬停到的元素;
  • :active 应用于被激活的元素;
  • :visited 应用于被访问过的链接

上述这4个的书写顺序:love hate(记忆方便)

结构伪类(css3新增选择器)

  • :first-child 匹配父元素中第一个子元素
  • :last-child 匹配父元素中最后一个子元素
  • :only-child 匹配父元素中仅有一个子元素的p元素
  • :nth-child(n) :匹配属于其父元素的第 N 个子元素,不论元素的类型
  • :nth-of-type(n) : 匹配属于父元素的第 N 个特定类型的子元素
<style>
   /* 匹配父元素中第一个子元素*/
    
    p:first-child {
        background-color: yellow;
    }
    /* 匹配父元素中最后一个子元素*/
    
    p:last-child {
        background: pink;
    }
    /* 匹配父元素中仅有一个子元素的p元素 */
    
    p:only-child {
        background: red;
    }
</style>
<body>
    <p>This paragraph is the first child of its parent (body).</p>
    <div>
        <p>This paragraph is the only child of its parent(div).</p>
    </div>
    <p> paragraph </p>
    <div>
        <p>This paragraph is the first child of its parent (div).</p>
        <p>This paragraph is the last child of its parent(div).</p>
    </div>


    <p><b>注意:</b> Internet Explorer 8以及更早版本的浏览器不支持 :only-child选择器.</p>
    <p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p>
</body>

在这里插入图片描述
:nth-child(n)与:nth-of-type(n)

<ul>
   <p>段落1</p>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

要选择ul中的第1个li元素的写法:
li:nth-child(2)或者li:nth-of-type(1)
在这里插入图片描述
在这里插入图片描述
二者的区别就是:
li:nth-child(n) 先考虑是父元素的第n个子元素的li
li:nth-of-type(n) 就是父元素的第n个li

伪元素

::before和::after
主要用来给元素的前面或后面插入内容,常用”content”配合使用

总结:
伪类:通常用作CSS选择器去设置更多的样式之类;
伪元素:创建一个有内容的虚拟容器;

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值