Apply CSS Style to child elements
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;
}
.test * {padding: 40px 100px 40px 50px;}
The >
selector matches direct children only, not descendants.
You want
div.test th, td, caption {}
or more likely
div.test th, div.test td, div.test caption {}
Edit:
The first one says
div.test th, /* any <th> underneath a <div class="test"> */
td, /* or any <td> anywhere at all */
caption /* or any <caption> */
Whereas the second says
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"> */
In your original the div.test > th
says any <th> which is a **direct** child of <div class="test">
, which means it will match <div class="test"><th>this</th></div>
but won't match <div class="test"><table><th>this</th></table></div>