CSS设置子元素的样式,常规的写法是这样:
/* CSS 代码 */
.papa { /* 父元素属性集 */ }
.papa .son { /* 子元素属性集 */ }
现在可以是这样:
/* CSS 代码 */
.papa {
/* 父元素属性集 */
.son { /* 子元素属性集 */ }
}
第二种写法父选择器嵌套了子选择器,好处是子选择器不用重复使用父选择器做前缀,同时父子选择器的逻辑关系更为清晰。下面的实例是一个 div 标签包含若干个 img 标签,对应的 CSS 选择器采用嵌套写法,可以在线预览效果:
<style>
.rot-div {
margin: auto;
width: 800px;
height: 800px;
border: 1px solid gray;
display: grid;
place-items: start center;
position: relative;
img {
position: absolute;
width: 50%;
transform-origin: 50% 100%;
transform: rotate(var(--a));
}
img:nth-of-type(1) { --a: 0deg; }
img:nth-of-type(2) { --a: 72deg; }
img:nth-of-type(3) { --a: 144deg; }
img:nth-of-type(4) { --a: 216deg; }
img:nth-of-type(5) { --a: 278deg; }
}
</style>
<div class="rot-div">
<img src="https://638183.freep.cn/638183/small/2026/f62.webp" alt="">
<img src="https://638183.freep.cn/638183/small/2026/f62.webp" alt="">
<img src="https://638183.freep.cn/638183/small/2026/f62.webp" alt="">
<img src="https://638183.freep.cn/638183/small/2026/f62.webp" alt="">
<img src="https://638183.freep.cn/638183/small/2026/f62.webp" alt="">
</div>
CSS父子选择器对标HTML父子容器,父嵌套子的选择器代码书写方法有很多相关知识,本例仅展现了最简单的层面。
|