将 CSS 样式应用于子元素

2022-01-10 00:00:00 css-selectors css

我只想将样式应用于具有特定类的 DIV 内的表:

注意:我宁愿为子元素使用 CSS 选择器.

为什么 #1 有效而 #2 无效?

1:

div.test th, div.test td, div.test 标题 {padding:40px 100px 40px 50px;}

2:

div.test th, td, caption {padding:40px 100px 40px 50px;}

HTML:

<html><头><风格>div.test >th,td,标题 {填充:40px 100px 40px 50px;}</风格></头><身体>

<表格边框="2"><tr><td>一些</td></tr><tr><td>数据</td></tr><tr><td>这里</td></tr></表></div><div 类="测试"><表格边框="2"><tr><td>一些</td></tr><tr><td>数据</td></tr><tr><td>这里</td></tr></表></div></身体></html>

我做错了什么?

解决方案

这段代码div.test th, td, caption {padding:40px 100px 40px 50px;}" 将规则应用于所有除了 all 之外,th 元素包含在具有名为 test 的类的 div 元素中td 元素和 所有 caption 元素.

它不同于一个divtdthcaption元素> 具有 test 类的元素".为此,您需要更改选择器:

'>' 不受某些旧浏览器的完全支持(我在看着你,Internet Explorer).

div.test th,div.test td,div.test 标题 {填充:40px 100px 40px 50px;}

I want to apply styles only to the table inside the DIV with a particular class:

Note: I'd rather use a css-selector for children elements.

Why does the #1 works and #2 doesn't?

1:

div.test th, div.test td, div.test caption {padding:40px 100px 40px 50px;}

2:

div.test th, td, caption {padding:40px 100px 40px 50px;}

HTML:

<html>
    <head>
        <style>
            div.test > th, td, caption {padding:40px 100px 40px 50px;}
        </style>
    </head>
    <body>
        <div>
            <table border="2">
                <tr><td>some</td></tr>
                <tr><td>data</td></tr>
                <tr><td>here</td></tr>
            </table>
        </div>
        <div class="test">
            <table  border="2">
                <tr><td>some</td></tr>
                <tr><td>data</td></tr>
                <tr><td>here</td></tr>
            </table>
        </div>
    </body>
</html>

What am I doing wrong?

解决方案

This code "div.test th, td, caption {padding:40px 100px 40px 50px;}" applies a rule to all th elements which are contained by a div element with a class named test, in addition to all td elements and all caption elements.

It is not the same as "all td, th and caption elements which are contained by a div element with a class of test". To accomplish that you need to change your selectors:

'>' isn't fully supported by some older browsers (I'm looking at you, Internet Explorer).

div.test th,
div.test td,
div.test caption {
    padding: 40px 100px 40px 50px;
}

相关文章