前端学习(11)选择器(基本、层次、结构伪类、属性)

选择器作用:选择页面上的某一个或者某一类元素

  • 基本选择器
    • 标签选择器:选择一类标签: 标签{}
    • 类选择器 class:选择所有class属性一致的标签,跨标签: .类名{]
    • Id选择器:全局唯一! #id名{}
      优先级:id > class > 标签
  • 层次选择器
    • 后代选择器
    • 子选择器
    • 相邻兄弟选择器
    • 通用兄弟选择器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        /*后代选择器*/
        body p {
            background-color: red;
        }
        /*子选择器,一代,儿子*/
        body>p{
            background-color: green;
        }
        /*相邻兄弟选择器:只有一个(相邻:向下)*/
        .active + p {
            background-color: aqua;
        }
        /*通用兄弟选择器,当前选中元素的向下的所有兄弟*/
        .active~p{
            background-color: black;
        }
    </style>
</head>
<body>

    <p class="active">p1</p>
    <p>p2</p>
    <p>p3</p>
    <ul>
        <li>
            <p>p4</p>
        </li>
        <li>
            <p>p5</p>
        </li>
        <li>
            <p>p6</p>
        </li>
    </ul>

</body>
</html>
  • 结构伪类选择器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--结构伪类选择器-->
    <style>
        /*ul的第一个子元素*/
        ul li:first-child{
            background-color: red;
        }
        /*ul的最后一个子元素*/
        ul li:last-child{
            background-color: green;
        }
        /*选中p1:定位到父元素,选择当前的第一个元素
        选择当前元素的父级元素,选中父级元素的第一个,并且是当前元素才生效
        (会被h1标签阻挡)
        */
        p:nth-child(1){
            background-color: aquamarine;
        }
        /*选中父元素下的p元素的第二个
        (不会被h1标签阻挡)
        */
        p:nth-of-type(2){
            background-color: bisque;
        }

        h1:hover{
            background: #ff5533;
        }
    </style>
</head>
<body>
    <h1>hello</h1>
    <p>p1</p>
    <p>p2</p>
    <p>p3</p>
    <ul>
        <li>l1</li>
        <li>l2</li>
        <li>l3</li>
    </ul>

</body>
</html>

在这里插入图片描述

  • 属性选择器
<style>
        /*存在id属性的元素*/
        a[id]{
            background: #ff5533;
        }
        /*id=first的元素*/
        a[id=first]{
            background: aquamarine;
        }
        /*class中包含links的元素*/
        a[class*="links"]{
            background: aqua;
        }
        /*选中href中以http开头的元素*/
        a[href^=http]{
            background: bisque;
        }
        /*选中href中以jpg结尾的元素*/
        a[href$=jpg]{
            background: black;
        }
    </style>

=是绝对等于
*=是包含
^=是以…开头
$=是以…结尾
这些都是通配符

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值