Tutorials Tonight's Logo
Follow Us

CSS ID SELECTOR


CSS id selector is used to select an element using the id attribute.

An id is used for many purposes like

  • selecting element using javascript for various purposes
  • creating page link
  • Adding CSS property to the element

Here in this section we will mainly focus on CSS implementation of id.



CSS Id

Same as CSS class we can use CSS id to add style to the element it is defined to. From CSS point of view there is no difference between class and id.

Unlike CSS class id can't be used more than once in any webpage.

An id is defined by id_name preceded by a hash symbol ("#") .

#id_name { property: value; }
#id1{
    background-color: #182C61;
    margin: 10px; /* There should be no space between value and unit */
    font-size: 20px;
}
#id2{
    color: #CAD3C8;
    padding: 25px;
}

Adding Id to an element

An id is added to an element by using the id attribute. As shown below

<p id="id1">This is a paragraph with an id.</p>

<!DOCTYPE html>
<html>
    <head>
        <style>
            #id1{
                background-color: #182C61;
                color: white;
                font-size: 20px;
                padding: 15px;
                width: 100%;
                }
        </style>
    </head>
<body>
    <h2>Learning about CSS id.</p>
    <p id="id1">This paragraph is added with id1.</p>
</body>
</html>
▶ Run the code

Output:

This paragraph is added with id1.

More Learning

Want to learn more about programming and web development? We have a few recommendations for you.


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.