To style an HTML element tag using an id
, you can use the id
attribute on the HTML element tag and then assign a unique name as the id to that element.
Since all the id
names should be unique, you cannot apply one id
to more than 1 element in the HTML.
For example, consider a p
(paragraph) tag with an id of pTag
in HTML like this,
<!-- Paragraph tag-->
<p id="pTag">Hello World!</p>
Now in the CSS stylesheet, we can apply the styles to the p
HTML tag by writing the name of the id.
To denote that we are using an id
in the CSS stylesheet we need to use the #
(hash character) before writing the name of the id.
It can be done like this,
/* Use the "pTag" id to set paragrah tag text color as red */
#pTag {
color: red;
}
This will apply a font color of red
to the text inside the p
(paragraph) HTML element tag.
See the above code live in JSBin.
How is it different from using the class
attribute?
When using the
class
attribute to style HTML elements, we can reuse the class names and apply them to more than 1 HTML element tag.But when using an
id
attribute, we cannot reuse it more than once.
That's all 😃!