ID selector


ID selector

You can apply styles to one identified element by using the ID selector.

An ID selector is a name preceded by a hash character (#).

#example { color: red; }

In the above example, the style is applied to one identified element that have the ID "example".

p#example { color: red; }

The ID can also be used with a particular element type. However, that element type is not usually necessary.

Note : An ID name cannot start with a number.
Bad example : #1example { }
Good example : #example1 { }

Element

You can specify an ID for an element by using the id attribute.

<p id="example">Example text</p>


<html>
<head>
<title>TAG index</title>

<style type="text/css">

#example1 { color: red; }
#example2 { color: gray; }

</style>

</head>
<body>

<h1 id="example1">This heading is red</h1>
<p id="example2">This text is gray.</p>

</body>
</html>

Nesting

The style can be applied only to elements within a certain element by using descendant selectors.

#example p { color: red; }

In the above example, the style is applied to all P elements within the element with the ID "example". (Other P elements are unaffected)


<html>
<head>
<title>TAG index</title>

<style type="text/css">

#example p { color: red; }

</style>

</head>
<body>

<div id="example">
<p>The style is applied to this text.</p>
<p>The style is applied to this text.</p>
</div>

<p>The style is not applied to this text.</p>

</body>
</html>