如何通过父元素ID在CSS中选择子元素?
通过父元素ID选择CSS子元素的方法
你写的代码完全可行,这是CSS里后代选择器的标准用法,能精准选中指定父元素下的所有目标子元素。
你的代码解析
你的写法没问题,最终会让ID为intro的<div>内部所有<p>元素文字变成红色:
#intro p { color: red; }
<div id="intro"> <p>Lorem ipsum dolor sit amet</p> </div>
扩展用法
- 仅选择直接子元素:如果只想选中
#intro的直接子级<p>(嵌套在其他元素里的<p>不生效),可以用子选择器>:#intro > p { color: red; } - 更精准的筛选:还能结合其他选择器细化范围,比如选中
#intro里的第一个<p>,或者带特定类的子元素:/* 选中#intro下的第一个<p> */ #intro p:first-child { font-weight: bold; } /* 选中#intro下带.text类的元素 */ #intro .text { line-height: 1.5; }
内容的提问来源于stack exchange,提问作者Dishum
相关产品推荐
相关产品推荐

