The :target Selector

Contact Us or call 1-877-932-8228
The :target Selector

The :target Selector

We use targets in URLs - that is, the attribute following the hash (#) in the URL - to open a given page not at the top of the page. A URL such as http://www.example.com/somepage.html#section1 would open the page somepage.html so that the element with id section1 is at the top of the browser (assuming there were enough content below the element to force a scroll). This is a useful way to link to specific content on a longer page.

CSS3 introduced the :target selector, a pseudo-class we can use to style the currently active target. A CSS rule such as

:target {
	background-color: #f00;
}

would style the linked-to element (a div, perhaps) with a red background color. The element would not be red if the element were not the current target. Here's a quick example:

Code Sample:

Links/Demos/Target.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CSS Target</title>
<style type="text/css">
	:target {
		background-color: #500000;
		border: 2px solid #000;
		color: #fff;
	}
	p {
		font-size: 20px;
		line-height: 24px;
		margin-bottom: 35px;
	}
</style>
</head>
<body>
<h1>CSS Target</h1>
<a href="#section1">Section 1</a><br>
<a href="#section2">Section 2</a><br>
<a href="#section3">Section 3</a><br>

<p id="section1">This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1. This is section 1.</p>
<hr>
<p id="section2">This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2. This is section 2.</p>
<hr>
<p id="section3">This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3. This is section 3.</p>
</body>
</html>

When first opened, the page displays two paragraphs with large text:

target

If the user clicks any of the links - all of which link to a target (either #section1, #section2, or #section3) - then the specified target receives the style from the :target selector, with a dark red background, white text color, and black border:

target - active
Next