CSS ID Selector


The CSS id selector is used to select a single element with a specific id. The id of an element is unique within a page, so the id selector is used to select one unique element!

An id is used for many purposes like:

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


CSS Id

Same as CSS class we can use CSS id to add style to the element in HTML.

From the CSS point of view, there is no difference between class and id selector. Both are used to select an element in HTML and add style to it.

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

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

Here is an example of a CSS id selector:

#id1 {
    background-color: #182C61;
    margin: 10px;
    font-size: 20px;
}

#id2 {
    color: #CAD3C8;
    padding: 25px;
}

Adding Id to an element

An id can be added to any element in HTML. It is added to an element using id attribute.

Here is an example of adding an id to an element and styling it using the CSS id selector:

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

Example

<style>
  #id1 {
    background-color: #ea8a74;
    color: white;
    font-size: 20px;
    padding: 15px;
    width: 100%;
  }
</style>

<body>
  <h2>Learning about CSS id.</p>
  <p id="id1">This paragraph is added with id1.</p>
</body>
Try it

Output:

This paragraph is added with id1.