选择子元素但不是孙子 [英] Selecting children elements but NOT grandchildren

查看:588
本文介绍了选择子元素但不是孙子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简化的代码:

 < div id =content > 
< p>文字< / p>

< div id =container>
< div id =col1>
< p>文字< / p>
< / div>
< div id =col2>
< p>文字< / p>
< / div>
< / div>

< p>文字< / p>
< / div>
< / div>

每当我在 #content p c>元素在CSS文件中,更改也适用于#col1 p #col2 p p>

我想要做的只是选择 #content <>的元素 p / code> div,而不是选择孙子 p 元素。





在CSS2或CSS3中有更好的方法吗?

解决方案

使用CSS大于符号> 子选择器):

  #content> p 




当一个元素是某个元素的子元素。



I have the following, simplified, code:

<div id="content">
    <p>text</p>

    <div id="container">
        <div id="col1">
            <p>text</p>
        </div>
        <div id="col2">
            <p>text</p>
        </div>
    </div>

    <p>text</p>
    </div>
</div>

Whenever I set some values to the #content p element in the CSS file, the changes also apply to the #col1 p and #col2 p.

What I would like to do is select only the children p elements of the #content div and not select the grandchildren p elements.

I imagine that one way of doing it would be to add a class to the first children and then apply properties throught it.

Is there any better way of doing it in either CSS2 or CSS3?

解决方案

Use the CSS Greater than sign > (Child selectors):

#content > p

A child selector matches when an element is the child of some element.

这篇关于选择子元素但不是孙子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆