css 基本选择器

85 阅读2分钟

按照这个文章写得

X Y

后代选择器 li下所有a元素字体颜色改变


li a {
    color:#fff;
}

.X.Y

选择同时包含XY类名的元素

X > Y

直接后代选择器 只有直接后台才会被选中


<div>

    <a>1</a>

    <div>

        <a>2</a>

    </div>

</div>


div > a{

color:red;

}

只有1红色

X + Y

邻近选择器(兄弟选择器) 紧跟这个的元素的后一个元素


<div><div>

<a>1</a>

<a>2</a>


div + a{
    color:red;
}

只有1变成红色

X ~ Y

这个与兄弟选择器很相近只不过没有那么严格,只要在X下的Y都会被选中


<div><div>

<a>1</a>

<a>2</a>

<div>3</div>

<a>4</a>


div ~ a{

color:red;

}

只有1,2,4变成红色

X[xxx]

属性选择器

  1. a[title] 含有title的a标签

  2. a[href="net.tutsplus.com"] href="net.tutsplus.com" 的a标签

  3. a[href*="nett"] href含有nett的a标签

  4. a[href^="http"] href以http开头的a标签

  5. a[href$=".jpg"] href以.jpg结尾的a标签

  6. a[data-*="foo"] 含有以data-开头的任意属性并且等于"foo"的a标签

X:not()

否定选择器

比如我想选择所有不是p标签的元素


*:not(p){color:red}

选择所有div并且不选择id位container的div


div:not(#container){color:red}

X::first-line

选中第一行(只能用于块元素)

X::first-letter

选中第一字母(只能用于块元素)

X:nth-child(n)

选中符合n的元素

X:nth-last-child(n)

与nth-child相同,但是是从后往前

X:nth-of-type(n)

通过元素类型来选择跟nth-child(n)类似,但是加了一个类型限制;


<ul>

<li>1</li>

<li>2</li>

<li>3</li>

</ul>

<div>4</div>

<div>5</div>

<ul>

<li>6</li>

</ul>


ul:nth-of-type(2){

color:red;

}

只有6变红色,因为ul:nth-of-type(2)选择器,限制是ul标签,并且选择的是第2个;

X:nth-last-of-type(n)

可以使用nth-last-of-type来选择倒数第n个元素。

X:first-child

选择母元素第一个子元素


<ul class="box active">

<li class="text">1</li>

<li class="text">2</li>

<li class="text">3</li>

</ul>


.box.active > li{

color:green;

}

.box > li:first-child{

color:red;

}

.box > li:last-child{

color:pink;

}

image.png

X:last-child

选择母元素最后一个子元素

X:only-child


<div>

<p> My paragraph here. </p></div>

<div>

<p> Two paragraphs total. </p>

<p> Two paragraphs total. </p>

</div>


div p:only-child {

color: red;

}

只有第一个div中的P标签会变红色,因为选择器是只选择div中只有一个P元素的标签

X:only-of-type

区别于nth-child于nth-of-type相同

X:first-of-type

选中某一个类型的第一个


<div>

<p> My paragraph here. </p>

<ul>

<li> List Item 1 </li>

<li> List Item 2 </li>

</ul>

<ul>

<li> List Item 3 </li>

<li> List Item 4 </li>

</ul>

</div>

怎么选中"List Item 2"?

方案1


ul:first-of-type > li:nth-child(2) {

font-weight: bold;

}

方案二


p + ul li:last-child {

font-weight: bold;

}

方案三


ul:first-of-type li:nth-last-child(1) {

font-weight: bold;

}