CSS id selector
Created By: chatGPT
CSS IDs are unique identifiers used to style individual elements on a web page. An ID begins with the
#
symbol followed by the name of the ID. It's important to note that each ID must be unique within a single HTML document, meaning no two elements can share the same ID. This allows for precise targeting of elements to apply specific styles./* Example of using an ID selector in CSS */
#header {
background-color: blue;
color: white;
padding: 10px;
text-align: center;
}
To use an ID selector, you first define an ID in your HTML element. For example, if you have a
<div>
with the ID header
, you can then reference it in your CSS by using the #
symbol. Remember only one element should have this ID to maintain its uniqueness.<div id="header">Welcome to My Website</div>
You can combine ID selectors with other selectors for more complex styling rules. Consider using class selectors or tag selectors in conjunction with ID selectors to create more specific styles.
#header h1 {
font-size: 24px;
font-weight: bold;
margin: 0;
}
In JavaScript, you can also easily manipulate elements with a specific ID. The
getElementById
method allows you to quickly access and alter elements by their ID, proving the versatility of using IDs in both CSS and JavaScript.const header = document.getElementById('header');
header.style.backgroundColor = 'red';