Say for example I have:
<div id="container"> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> </div>
And
td { width:10px; height:10px; }
What I want to do is apply a style to the first td, of the first table.
I would have expected:
#container table:first-child td:first-child { background: red; }
However it does not work? Please advise!
This can be achieved using :nth-of-type() instead of :nth-child() , as the former only considers elements of the same type when calculating their indices. Note though that both :nth-child() and :nth-of-type() are only supported in IE9 and above.
The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
The :first-child selector is a pseudo-class that allows you to target an element that is the first child element within its parent. See also :last-child, :nth-child, :nth-last_child, and :only-child selectors.
You could also have table > thead > tr and then table > tbody > tr. So you might need to specify whether you want the first row from the thead or the tbody. find('tr:first') will select the tr in the thead. – Jeff S.
CSS :first-child Selector 1 Definition and Usage. The :first-child selector is used to select the specified selector, only if it is the first child of its parent. 2 Browser Support. The numbers in the table specifies the first browser version that fully supports the selector. 3 CSS Syntax 4 More Examples 5 Related Pages
#container table:first-child td:first-child { background: red; } However it does not work? Please advise! Show activity on this post. Seems to work.
First, create HTML. Use a <table> element and set the width through the style attribute. Add a <th> element with the colspan attribute. Use two <tr> elements and place <td> elements inside.
To specify table borders in CSS, use the border property. The example below specifies a black border for <table>, <th>, and <td> elements: The table above might seem small in some cases.
#container table:first-child tr:first-child td:first-child { background: red; }
Seems to work.
Note that under IE, you will need to have a !DOCTYPE declaration in your html to get support for :first-child. http://www.w3schools.com/cssref/sel_firstchild.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With