XHTML and CSS - Child Selectors
Child Selectors
In this tutorial we are going to be looking at how to style a child selector. A child selector is a tag that's inside another tag, for example the body tag has to be between the HTML tags, or the style tags have to be in the header tags, the style tag would be the child of the header tags and the header tags would be called the parent tags of the style tags. Let's say I want some links and I only want to style the links that are in paragraph tags, the first thing we need to do is create two links, one in a paragraph and one not in a paragraph.
<html> <head> <title> This is the title. </title> <style type="text/css"> </style> </head> <body> <a href="https://aboredcoder.com/">This is a normal Link.</a> <p> <a href="https://aboredcoder.com/">This is a link in a paragraph.</a> </p> </body> </html>
When you view this in your browser you'll see that both of the links look the same, now let's style the link that's in the paragraph using a child selector. First we need to tell CSS that we want to style all of the a tags in the paragraph tags, you can do that by selecting the paragraph element, then putting a greater then sign and then putting the a element. All I'm going to do to the link element is change the text color to green.
<html> <head> <title> This is the title. </title> <style type="text/css"> p > a { color: green; } </style> </head> <body> <a href="https://aboredcoder.com/">This is a normal Link.</a> <p> <a href="https://aboredcoder.com/">This is a link in a paragraph.</a> </p> </body> </html>
Now when you view the page you'll see that the link outside of our paragraph is normal but the link that is between our paragraph tags is now green. You also could have a link inside of a paragraph inside of a div, this would make the link the grandchild and you could select that with div > p > a, here is a quick example of changing that element to have red text.
<html> <head> <title> This is the title. </title> <style type="text/css"> p > a { color: green; } div > p > a { color: red; } </style> </head> <body> <a href="https://aboredcoder.com/">This is a normal Link.</a> <p> <a href="https://aboredcoder.com/">This is a link in a paragraph.</a> </p> <div> <p> <a href="https://aboredcoder.com/">This is a link in a paragraph that's in a div.</a> </p> </div> </body> </html>
When you view that you'll see that the link that's a grandchild of the div tag is red while the others are unchanged.

Page generated in 0.0049 seconds.