Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 268
roman m Avatar asked Mar 10 '09 20:03

roman m


People also ask

How do you not apply CSS to child elements?

The > is the child selector, which prevents the style from being applied to table rows further down the element tree. Show activity on this post. One solution would be to name your style table tr. style1{ ... and then in each of your <tr> 's you could just add a class attribute, i.e. <tr class="style1"> .

Can CSS be used to find child => parent page element?

There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers.


2 Answers

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; } 
like image 172
Ken Browning Avatar answered Oct 05 '22 16:10

Ken Browning


.test * {padding: 40px 100px 40px 50px;} 
like image 45
Richard Edwards Avatar answered Oct 05 '22 16:10

Richard Edwards