Individualizing Styles: Applying CSS with ID Selectors
Master the art of precision styling by targeting unique elements with the powerful CSS ID selector.
An Element
Welcome! Today, we'll learn to style one specific element using a CSS ID selector.
/* Let's target a unique element! */
Syntax of ID Selectors
An ID selector is defined by a hash symbol (#
) followed by the ID name. For example, to select the single element with the attribute id="main-header"
, you would write the CSS rule #main-header { ... }
.
The Rule of Uniqueness & Specificity
Unlike classes, an ID must be unique to a single element on a page. This gives the ID selector very high specificity, meaning its styles are powerful and difficult to override by other selectors like classes or tags.
Practice Zone
Interactive Test 1: Drag & Drop
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Fill in the Blanks
Rellena los huecos en cada casilla.
#footer { background-color: ; }
Practice Example: Code Editor
Write a CSS rule to change the text color of the element with the ID title
to green.
A Practical Guide to Using CSS IDs
ID selectors are your tool for precision styling. They are perfect for unique, high-level elements that define your page's structure and for creating specific interaction points.
1. Structuring Your Page with IDs
It's a common best practice to use IDs for the main structural elements of your page, like the header, main content area, and footer. This makes both your CSS and HTML more readable.
/* CSS */
#main-header {
background-color: #4f46e5;
color: white;
padding: 1rem;
}
2. ID vs. Class: The Specificity Battle
What happens when an element has both an ID and a class that apply competing styles? The ID always wins due to its higher specificity. This makes IDs reliable for overriding more general styles.
/* HTML: <div id="unique-box" class="blue-box"></div> */
/* CSS */
#unique-box {
background-color: red; /* This one wins! */
}
.blue-box {
background-color: blue;
}
3. IDs for Page Anchors and JavaScript
IDs serve a dual purpose. They can be used as anchor links (<a href="#contact-form">
) to jump to a specific part of a page. They're also the most common way for JavaScript to find and manipulate a single, specific element on the page.
// JavaScript
const title = document.getElementById('main-title');
title.textContent = 'Welcome, User!';
IDs are essential hooks for interactivity.
Practical Takeaway: Use IDs for unique, structural elements (one per page). Use classes for reusable styles that can be applied to many elements. This separation of concerns is key to scalable and maintainable CSS.