CSS选择器总结

前言:CSS中的选择器比较多,但是平时自己在书写代码的时候使用的并不多,这里对其进行一个总结

常见选择器
p {
    color: #ccc;
}
p a {
    font-size: .8rem;
}
#content {
    margin: 0 auto;
}
.header {
    height: 200px;
}
a:link {
    color: blue;
}
a:visited {
    color: green;
}
a:hover,
a:focus,
a:active {
    color: red; 
}
//已经访问的链接
a:visited:hover {
    color: gray;
}
通用选择器
//不建议这样使用
* {
    padding: 0;
    margin: 0;
}
//li下面的所有元素
#nav li * {
    background: red;
}
高级选择器
//子选择器只是选择直接后台,而后台选择器则是选择所有后代
#nav>li {
    list-style: none;
}
//相邻选择器,设置h2和h2下面第一个p标签的样式
h2 + p {
    font-size: 1.6em;
    font-weight: 600;
}
//属性选择器
a[rel='follow'] {
    padding-right: 30px;
}
//title中函数flower,例如title="flower" title="blue flower",对于flower_one不能够选择
[title~=flower] {
    width: 30px;
    height: 30px;
    background-color: orange;
}
//first-letter 每个段落的第一个字符
p:first-letter {
    color: red;
}
//first-line 每个段落的第一行
p:first-line {
    color: red;
}
//first-child 选择父级元素的第一个p元素,这里父元素可以是body
//注意这里没有second-child
p:first-child{
    color: orange;
}
//last-child 选择父级元素的最后一个p元素
p:last-child {
    color: orange;
}
//before 每个p元素之前插入内容
p:before {
    content: "welcome";
    clear: both;
}
//after 每个p元素之后插入内容
p:after {
    content: "see you";
    clear: both;
}
//~ 父元素相同,p元素后面的所有ul元,这里body也当做父元素处理
p~ul {
    color: orange;
}
//^ src以https开头的元素
a[src^="https"] {
    color: orange;
}
//$ src以com结尾的元素
a[src$=".com"] {
    color: orange;
}
//* class中包含test的元素,test_one,onetesting这些都是可以选择
div[class*="test"] {
    color: orange;
}
//first-of-type 这个和first-child一样
//last-of-type 这个和last-child一样
//only-of-type 选择父级元素只有一个p元素的p元素
p:only-of-type {
    color: red;
}
//only-child 选择父级元素只有一个子元素的p元素(也就是一个div中只有一个p标签才可以选择)
p:only-child {
    color: red;
}
//nth-child(n) 选择父级元素的第n个p元素,first-child的扩展,这里我们可以指定第几个,注意这里是从1开始,不是从0开始计数
p:nth-child(2) {
    color: red;
}
//奇数行
p:nth-child(odd) {

}
//偶数行
p:nth-child(even) {
}
//nth-last-child(n) 和nth-child(n)类似,只是这里是从后向前计数
p:nth-last-child(2) {
    color:red;
}
//nth-of-type(n)这个和nth-child(n)一样
//nth-last-of-type(n) 这个和nth-last-child(n)一样
//empty 元素p中没有内容
p:empty{
    background: orange;
}
//target 这个选择器主要用在锚点,当通过锚点跳转到这里的时候,会执行目标选择器中的内容
p:target{
    color: red;
}
<a href="#news1">content1</a></p>
<p><a href="#news2">content2</a></p>

<p id="news1">内容 1...</p>
<p id="news2">内容 2...</p>
//enabled 主要对于input使用,可以输入的input
input:enabled {
    backgound: white;
}
//disabled 主要对于input使用,不可以输入的input
input:disabled {
    background: gray;
}
选择器的特殊性

特殊性越高就以它为准,如果特殊性相同,那么就写在后面的为准

#content {
    100
}
.content {
    10
}
p{
    1
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值