热搜: 活动 交友 discuz
查看: 278|回复: 1

马黑黑老师《CSS父选择器嵌套子选择器》

[复制链接]
发表于 2026-6-3 21:24:49 | 显示全部楼层 |阅读模式

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父子容器,父嵌套子的选择器代码书写方法有很多相关知识,本例仅展现了最简单的层面。

200

主题

1139

回帖

1万

积分

社区贵宾

积分
16110

最佳新人活跃会员热心会员推广达人宣传达人灌水之王突出贡献

发表于 2026-6-4 21:48:54 | 显示全部楼层
父子选择器新写法,学习了
该会员没有填写今日想说内容.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|小黑屋|纳兰音画网 ( 蜀ICP备2021011087号-1 )

GMT+8, 2026-11-16 09:18 , Processed in 0.048237 second(s), 22 queries .

Powered by Discuz! X5.0

© 2001-2020 Comsenz Inc.

快速回复 返回顶部 返回列表