CSS选择器

基本选择器(重要)

1. 标签选择器
标签 {}

2. 类选择器
.类名 {}

3. id选择器
#id名 {}

优先级
id > 类 > 标签

层次选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="style.css">
</head>
<body>

<p class="season">春</p>
<p class="sky">夏</p>
<p>秋</p>
<p>冬</p>
<ul>
    <li><p>播种</p></li>
    <li><p>施肥</p></li>
    <li><p>收获</p></li>
</ul>

</body>
</html>
/*后代选择器
后面层次中所有相同标签都被选中*/
body p{
    color: #28d039;
}

/*子选择器
后面层次中只有第一代标签被选中*/
body>p {
    color: #de1b1b;
}

/*相邻兄弟选择器
只选中同一层次后面最近的一个相同标签*/
.season + p {
    color: darkcyan;
}

/*通用兄弟选择器
同一层次后面所有相同标签都被选中*/
.sky ~ p {
    color: dodgerblue;
}

结构伪类选择器

  • 伪类:同一个标签,根据不同状态有不同的样式
  • 用冒号表示过滤
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="style.css">
</head>
<body>

<p>春</p>
<p>夏</p>
<p>秋</p>
<p>冬</p>
<ul>
    <li><p>播种</p></li>
    <li><p>施肥</p></li>
    <li><p>收获</p></li>
</ul>

<a href="">link</a>

</body>
</html>
/*1. 根据顺序,选择同一级第一个子元素*/
ul li:first-child {
    background: darkcyan;
}

/*2. 根据顺序,选择同一级最后一个子元素*/
ul li:last-child {
    background: #da2ae7;
}

/*3. 选择父级的某一个子元素,该子元素与p同类型
    要求p必须是父级的第一个子元素*/
p:nth-child(1) {
    background: #28d039;
}

/*4. 选择父级同一类型标签的某一个子元素,该子元素与p同类型
    不要求p必须是父级的第一个子元素*/
p:nth-of-type(1){
    background: dodgerblue;
}

/*测试伪类不同状态显示不同样式*/
a:hover {
    background: aqua;
}

属性选择器(重要)

  • 标签名[属性正则表达式] {}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css.css">
</head>
<body>


<p class="demo">

    <a href="http://www.baidu.com" class="links item first" id="first">1</a>
    <a href="http://blog.kuangstudy.com" class="links item active" target="_blank" title="test">2</a>
    <a href="images/123.html" class="links item">3</a>
    <a href="images/123.png" class="links item">4</a>
    <a href="images/123.jpg" class="links item">5</a>
    <a href="abc" class="links item">6</a>
    <a href="/a.pdf" class="links item">7</a>
    <a href="/abc.pdf" class="links item">8</a>
    <a href="abc.doc" class="links item">9</a>
    <a href="abcd.doc" class="links item last">10</a>

</p>

</body>
</html>
.demo a{
    float: left;
    display: block;
    height: 50px;
    width: 50px;
    border-radius: 10px;
    background: #2700ff;
    text-align: center;
    color: gainsboro;
    text-decoration: none;
    margin-right: 5px;
    font: bold 20px Arial;
    line-height: 50px;
}

/* 属性名 = 属性值(正则表达式)
= 绝对等于
*= 包含这个元素
^= 以这个开头
$= 以这个结尾
*/

/*存在id属性的元素,a[]{}*/
/*a[id]{*/
/*background: yellow;*/
/*}*/

/*id=first的元素*/
/*a[id=first]{*/
/*background: #63ff23;*/
/*}*/

/*class中有links的元素*/
a[class*=links]{
    background: yellow;
}

/*!*选中href中以http开头的元素*!*/
/*a[href^=http]{*/
/*background: yellow;*/
/*}*/

/*a[href$=jpg]{*/
/*    background: yellow;*/
/*}*/
posted @ 2020-09-27 11:22  CrazyGod  阅读(134)  评论(0)    收藏  举报