您好,欢迎访问一九零五行业门户网

使用 CSS 选择同级元素

如果我们想要匹配紧跟在第一个选择器后出现的元素,我们可以使用相邻兄弟选择器(+)。在这里,两个选择器都是同一个父元素的子元素。
css相邻兄弟组合器的语法如下:
selector + selector{ attribute: /*value*/}
如果我们想选择同一父元素下的兄弟元素,不考虑第二个选定元素的位置,我们可以使用css通用兄弟选择器。
css通用兄弟选择器的语法如下:
selector ~ selector{ attribute: /*value*/}
下面的例子演示了css相邻和一般兄弟选择器属性。
例子 演示
<!doctype html><html><head><style>#parent { display: flex; margin: 2%; padding: 2%; box-shadow: inset 0 0 24px cyan; justify-content: space-around;}div + p { font-size: 1.2em; font-weight: bold; background: powderblue;}section { box-shadow: 0 0 3px rgba(0,0,0,0.8);}</style></head><body><div id="parent"><img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=qezyezu6nvn4d_vdalhst9uattuevhwrt-km5ogbqkm" /><div><p>check this</p><section><p>some text in section</p></section><span>hello</span></div><p>selected</p></div></body></html>
输出这将产生以下结果 -
示例 现场演示
<!doctype html><html><head><style>#parent { display: flex; margin: 2%; padding: 2%; background: thistle; justify-content: space-between;}section ~ p { text-align: center; font-size: 1.2em; font-weight: bold; background: lavender;}</style></head><body><div id="parent"><img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=qezyezu6nvn4d_vdalhst9uattuevhwrt-km5ogbqkm" /><div><p>random text 1</p><section><p>some text in section</p></section><span>hello</span><p>selected</p></div><img src="https://i.picsum.photos/id/1035/200/200.jpg?hmac=iduyuzq_7a6h4pqu2k7p2nxtmjmt4uy-p3ze94kta4" /></div></body></html>
输出这将产生以下结果 −
以上就是使用 css 选择同级元素的详细内容。
其它类似信息

推荐信息