一文学会CSS基本选择器和复合选择器

html-css016

一文学会CSS基本选择器和复合选择器,第1张

要想为指定的HTML元素添加CSS样式,首先需要选中该元素。在CSS中,执行这一选择操作规则部分被称为选择器(选择符)。

CSS基本选择器可以分为五类:标签选择器、id选择器、类选择器、通配符选择器和伪类选择器。

多类名选择器

可以给单个标签添加多个类名,既可以提升类样式的复用性,也可以达到添加多种样式的效果。在后面复杂网页的布局中使用较多。

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" cid="n2260" mdtype="fences" style="box-sizing: border-boxoverflow: visiblefont-family: var(--monospace)font-size: 0.9emdisplay: blockbreak-inside: avoidtext-align: leftwhite-space: normalbackground-image: inheritbackground-position: inheritbackground-size: inheritbackground-repeat: inheritbackground-attachment: inheritbackground-origin: inheritbackground-clip: inheritbackground-color: rgb(248, 248, 248)position: relative !importantborder: 1px solid rgb(231, 234, 237)border-radius: 3pxpadding: 8px 4px 6pxmargin-bottom: 15pxmargin-top: 15pxwidth: inherit"><div class="pink fontWeight font20">苹果</div>

<div class="font20">香蕉</div>

<div class="font14 pink">橘子</div>

<div class="font14"></div></pre>

通配器选择器用“*”号表示,它是所有选择器中作用范围最广的,能匹配页面中所有的元素。

常用的结构伪类选择器:

:target 选择器

可用于选取当前活动的目标元素,然后给它添加相应的样式。

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded md-focus" lang="css" cid="n2337" mdtype="fences" style="box-sizing: border-boxoverflow: visiblefont-family: var(--monospace)font-size: 0.9emdisplay: blockbreak-inside: avoidtext-align: leftwhite-space: normalbackground-image: inheritbackground-position: inheritbackground-size: inheritbackground-repeat: inheritbackground-attachment: inheritbackground-origin: inheritbackground-clip: inheritbackground-color: rgb(248, 248, 248)position: relative !importantborder: 1px solid rgb(231, 234, 237)border-radius: 3pxpadding: 8px 4px 6pxmargin-bottom: 15pxmargin-top: 15pxwidth: inherit"><h2><a href="#brand">Brand</a></h2>

<div id="brand">

content for Brand

</div>

background: orange

color: #fff

}</pre>

复合选择器是由两个或多个基本选择器,通过不同的方式组合而成的,目的是为了更准确、更精细的选择目标元素标签。

复合选择器的三种类型:交集选择器、并集选择器、后代选择器、子选择器以及相邻元素选择器。

1、CSS兄弟相邻选择器加号

相邻兄弟选择器使用了加号(+),即相邻兄弟结合符(Adjacent sibling combinator)。

注释:与子结合符一样,相邻兄弟结合符旁边可以有空白符。

CSS兄弟相邻选择器加号,举例说明

HTML代码

<p>这里是第一个P标签</p><p>这里是第二个P标签</p><h2 class = 'h2'>标题H2</h2><p>这里是第一个P标签</p><p>这里是第二个P标签</p><p>这里是第三个P标签</p><p>这里是第四个P标签</p>

CSS代码

.h2 + p{

    color: red

  }

2、CSS兄弟选择器~(匹配选择器)

'~'匹配所有在指定元素之后的同级某个元素

举例说明一个,CSS的匹配选择器

HTML代码

<p>这里是第一个P标签</p><p>这里是第二个P标签</p><h2 class = 'h2'>标题H2</h2><p>这里是第一个P标签</p><p>这里是第二个P标签</p><p>这里是第三个P标签</p><p>这里是第四个P标签</p>

CSS代码

.h2 ~ p{

    color: red

    }

3、总结:

CSS中的兄弟选择符号‘~’,可以选择指定元素后的,同级的相同的所有元素。比如上面的示例,所以h2标签后的P标签全部被选择,并加入了样式

通过这两个例子,可以发现虽然这两个选择器都表示兄弟选择器,但是‘+’选择器则表示某元素后相邻的兄弟元素,也就是紧挨着的,是单个的。而‘~’选择器则表示某元素后所有同级的指定元素,强调所有的。

其他选择器可参考