CSS nth-child Selector
By Stephen Bucaro
This Example Requires Your Browser to Allow Pop-ups
Since Chrome is by far the most popular browser, here is how to allow pop-ups in
Chrome. By default, Chrome blocks pop-ups.
1. Open Chrome.
2. At the top right, click the three dots (Customize and control Google Chrome).
3. In the menu that appears, select Settings.
4. Scroll down to the bottom of the Settings page that appears.
5. At the bottom of the Settings page click Advanced.
6. Under "Privacy and security," click Content settings.
7. Click Popups.
8. On the Popups page, at the top, turn the setting to Allowed.
9. Close the Settings tab.
When you have completed this examples article, to return to blocking popups, follow
the same steps above except in step 8 return the setting to Blocked.
In order to apply a style to an html element on a webpage, you must first select
the element. There are many ways to select an element on a webpage, ranging from the
CSS3 * selector, which selects every element in the document, to the # selector,
which selects only an element with a specific id. In this article, I describe the CSS3
nth-child selector. The nth-child selector is used to reference elements
that are a child of another element.
The example below shows code for a div element that has five p child
elements. The nth-child selector is used to set the font for the third child
element to bold.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div p:nth-child(3)
{
font-weight:bold;
}
</style>
</head>
<body>
<div>
<p>Paragraph one</p>
<p>Paragraph two</p>
<p>Paragraph three</p>
<p>Paragraph four</p>
<p>Paragraph five</p>
</div>
</body>
</html>
Show Example
The example below shows how to set a style for all the child elements, i.e. the
font-family is set for the parent element and is inherited by all the child
elements. Then the nth-child selector is used to set the font for the third
child element to bold.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#myDiv
{
font-family:verdana;
}
p:nth-child(3)
{
font-weight:bold;
}
</style>
</head>
<body>
<div id="myDiv">
<p>Paragraph one</p>
<p>Paragraph two</p>
<p>Paragraph three</p>
<p>Paragraph four</p>
<p>Paragraph five</p>
</div>
</body>
</html>
Show Example
|