What is Id Attribute?
In HTML, the 'id attribute' is used to uniquely identify an HTML element within a document.
The value of the id attribute must be unique across the whole document. No two elements in the same HTML page should have the same id.
CSS and JavaScript can target an HTML element with the unique id value to apply CSS styles or define behaviors.
To add an id attribute in an HTML element, you need to add id="id-value" in the opening tag of an HTML element.
Adding Id Attribute to an HTML Element
In the following example, we have a paragraph (<p>) element with an id value "test" at the opening tag as id="test". Here id is the HTML id attribute and "test" is the id value. "test" can be used to target and apply CSS style to the paragraph element.
Here id="test" is the HTML id attribute.
Example of HTML Id Attribute
Adding Internal CSS Style Using 'id' Attribute
To define an ID selector in CSS style, a hash (#) sign must be put before the id name (i.e. #test). CSS properties are defined within curly braces { } after the class name. Multiple CSS properties can be defined in the curly braces separated by semicolon ;.
In the following example, we have added HTML <style> tag between the <head> and </head> tag; it is known as internal CSS style. Inside the style element, we have added CSS ID selector #test.
color and font-size CSS properties have been set in the ID selector. Color has been set to 'red' and font-size has been set to '18px'.
Here #test" is the CSS ID selector.
Thus, we have targeted the HTML paragraph element using its id attribute (id="test") and CSS ID selector (#test).
Review the example closely.
Example of Adding CSS Style Using 'id' Attribute
Output of the above example
You can use HTML id attribute value as selector to add style to the element within head element to apply CSS style.