css基础知识 -- 选择器

1.css选择器: 用于“查找”(或选取)要设置样式的 HTML 元素;选择器种类分为5类

1.1简单选择器

1.1.1 元素选择器:根据元素名称来选择 HTML 元素

p {
  text-align: center;
  color: green;
}

1.1.2 id 选择器:使用 HTML 元素的 id 属性来选择特定元素(元素的 id 在页面中是唯一的,因此 id 选择器用于选择一个唯一的元素)

#text {
  text-align: center;
  color: green;
}
//id 名称不能以数字开头

1.1.3 类选择器:选择有特定 class 属性的 HTML 元素

//类名不能以数字开头
.text {
  text-align: center;
  color: green;
}
//还可以指定只有特定的 HTML 元素会受类的影响
p .text {
  text-align: center;
  color: green;
}
//HTML 元素也可以引用多个类
...
<style>
p.center {
  text-align: center;
  color: green;
}

p.large {
  font-size: 300%;
}
</style>
...
<p class="center large">本段将是绿色、居中对齐,并使用大字体。</p> 
...

1.1.4 通用选择器(*):选择页面上的所有的 HTML 元素

* {
  text-align: center;
  color: green;
}

1.1.5 分组选择器:选取所有具有相同样式定义的 HTML 元素

h1 {
  text-align: center;
  color: green;
}

h2 {
  text-align: center;
  color: green;
}

h3 {
  text-align: center;
  color: green;
}

//如需对选择器进行分组,请用逗号来分隔每个选择器
h1, h2, h3 {
  text-align: center;
  color: green;
}

1.2 组合器选择器

组合器是解释选择器之间关系的某种机制

1.2.1 后代选择器:匹配属于指定元素后代的所有元素

<div>元素内包含的所有<p>元素的背景色为绿色(只要是在<div内的都匹配>)

div p {
  background-color: green;
}

<div>
  <p>div 中的段落 1。</p>
  <p>div 中的段落 2。</p>
  <section><p>div 中的段落 3。</p></section>
</div>

1.2.2 子选择器:匹配属于指定元素子元素的所有元素

<div>的子元素才匹配,段落3是<section>元素的子元素,所以它不匹配

div > p {
  background-color: green;
}

<div>
  <p>div 中的段落 1。</p>
  <p>div 中的段落 2。</p>
  <section><p>div 中的段落 3。</p></section>
</div>

1.2.3相邻兄弟选择器:匹配所有作为指定元素的相邻同级的元素(兄弟(同级)元素必须具有相同的父元素,“相邻”的意思是“紧随其后”)

h1 + p {
  background-color: green;
}

<h1>相邻兄弟选择器</h1>
<p>相邻的同胞选择器(+)选择所有作为指定元素的相邻的同级元素。</p> // 变成绿色背景

1.2.4通用兄弟选择器:匹配属于指定元素的同级元素的所有元素

div ~ p {
  backgrou
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值