对子元素应用CSS样式

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

注意:我宁愿为子元素使用css选择器。

为什么第一条可行,第二条不行?

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>

我做错了什么?

720073 次浏览

这段代码"div.test th, td, caption {padding:40px 100px 40px 50px;}"对类名为testdiv元素所包含的所有th元素应用规则,此外还有所有 td元素和所有 caption元素。

它与“类为testdiv元素所包含的所有tdthcaption元素”不同。要做到这一点,你需要改变你的选择器:

'>'不完全支持一些旧的浏览器(我指的是你,Internet Explorer)。

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

据我所知:

div[class=yourclass] table {  your style here; }

或者在你的情况下甚至是这样:

div.yourclass table { your style here; }

(但这适用于带有yourclass的可能不是__abc1的元素)将只影响yourclass内的表。而且,正如Ken所说,>并不是在任何地方都受支持(div[class=yourclass]也是如此,所以对类使用点符号)。

> 选择器只匹配直接子代,不匹配子代。

你想要的

div.test th, td, caption {}

或者更有可能

div.test th, div.test td, div.test caption {}

编辑:

第一个说

  div.test th, /* any <th> underneath a <div class="test"> */
td,          /* or any <td> anywhere at all */
caption      /* or any <caption> */

而第二种说法是

  div.test th,     /* any <th> underneath a <div class="test"> */
div.test td,     /* or any <td> underneath a <div class="test"> */
div.test caption /* or any <caption> underneath a <div class="test">  */

在你的原文中,div.test > th表示any <th> which is a **direct** child of <div class="test">,这意味着它将匹配<div class="test"><th>this</th></div>,但不会匹配<div class="test"><table><th>this</th></table></div>

div.test td, div.test caption, div.test th

对我有用。

子选择器>在IE6中无法工作。

.test * {padding: 40px 100px 40px 50px;}

下面是我最近写的一些代码。我认为它提供了将类/ID名与伪类结合的基本解释。

.content {
width: 800px;
border: 1px solid black;
border-radius: 10px;
box-shadow: 0 0 5px 2px grey;
margin: 30px auto 20px auto;
/*height:200px;*/


}
p.red {
color: red;
}
p.blue {
color: blue;
}
p#orange {
color: orange;
}
p#green {
color: green;
}
<!DOCTYPE html>
<html>


<head>
<title>Class practice</title>
<link href="wrench_favicon.ico" rel="icon" type="image/x-icon" />
</head>


<body>
<div class="content">
<p id="orange">orange</p>
<p id="green">green</p>
<p class="red">red</p>
<p class="blue">blue</p>
</div>
</body>


</html>

如果你想添加样式在所有的孩子和没有规范的html标签,然后使用它。

父标签div.parent

div.parent中的子标签,如<a><input><label>等。

代码:div.parent * {color: #045123!important;}

你也可以删除重要的,它不是必需的

使用SCSS语法,这段代码也可以做到这一点

.parent {
& > * {
margin-right: 15px;
&:last-child {
margin-right: 0;
}
}
}