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

html-css07

一文学会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>

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

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

.opacity-0 {

opacity: 0

}

.m0-auto {

margin: 0 auto

}

.m0 {

margin: 0

}

.p0 {

padding: 0

}