Chapter 3 CSS (Define ID in CSS)
In HTML and CSS, an ID (identifier) is a unique attribute used to identify an individual element on a webpage. Each ID must be unique within the document, distinguishing one element from all others.
HTML ID attribute:
In HTML, the ID attribute uniquely identifies an element.
<div id="uniqueID">This is a box with a border and padding.</div>
- 1. The
id
attribute is placed inside an HTML tag to give that element a unique identifier. - 2. It should be a string without spaces and should start with a letter (can also contain digits, underscores, and hyphens).
- 3. IDs should be used for uniquely identifying specific elements.
CSS Usage of IDs:
In CSS, you can use IDs to target and style specific HTML elements:
#uniqueID { /*CSS styles for the element with the ID "uniqueID"*/ border: 1px solid #000; padding: 10px; }
- 1. To style an element with a specific ID, the hash symbol (
#
) is used followed by the ID name. - 2. IDs are highly specific selectors in CSS, providing a more direct and high-priority way to style elements.
- 3. IDs should be used when styling unique elements or when you want to apply specific styles to a particular element.
Points to Consider:
- 1. Uniqueness: IDs must be unique within an HTML document. Using the same ID for multiple elements is invalid HTML and might lead to unexpected behavior.
- 2. Specificity: In CSS, IDs have a higher specificity than classes or tag selectors, which means their styles will override styles from classes or tags.
- 3. JavaScript: IDs are often used in JavaScript to target specific elements for DOM manipulation or event handling.
Example:-
<html>
<head>
<style>
#highlight {
color: red;
font-weight: bold;
}
#uniqueID {
/*CSS styles for the element with the ID "uniqueID"*/
border: 1px solid #000;
padding: 10px;
}
</style>
</head>
<body>
<!-- HTML content with applied classes -->
<p id="highlight">This text is styled using the 'highlight' class.</p>
<div id="uniqueID">This is a box with a border and padding.</div>
</body>
</html>
Result:-