ID Selectors in CSS (Live Playground)
ID selectors in CSS allow you to target and style HTML elements based on their ID attributes. This enables you to apply specific styles to unique elements on your web page. In this tutorial, you will learn how to use ID selectors effectively, along with sample code and simple explanations.
Using ID selectors
To target an HTML element using an ID selector, write a hash symbol (#
) followed by the ID name in your CSS file. The styles within the declaration block will be applied to the element with the specified ID attribute.
Example:
/* Target the element with the ID "main-header" */
#main-header {
font-family: Arial, sans-serif;
font-size: 24px;
color: darkblue;
}
<h1 id="main-header">This is the main header of the page.</h1>
In this example, the ID selector #main-header
targets the header element with the ID "main-header" and applies the specified font-family, font-size, and color styles.
Combining ID selectors
Though it is uncommon, you can target multiple elements with different ID attributes by listing the ID names as a comma-separated list. The styles within the declaration block will be applied to all elements with the specified ID attributes.
Example:
/* Target elements with the IDs "top-banner" and "bottom-banner" */
#top-banner,
#bottom-banner {
background-color: lightgray;
padding: 20px;
}
<div id="top-banner">Top banner content</div>
<div id="bottom-banner">Bottom banner content</div>
In this example, the ID selectors #top-banner
and #bottom-banner
target the div elements with the specified ID attributes and apply the background-color and padding styles.
ID selectors with element selectors
ID selectors can be combined with element selectors to target an element of a specific type with a particular ID attribute.
Example:
/* Target a div element with the ID "content-wrapper" */
div#content-wrapper {
margin: 20px;
border: 1px solid black;
}
<div id="content-wrapper">This is the content wrapper.</div>
In this example, the selector div#content-wrapper
targets only a div element with the ID "content-wrapper" and applies the specified margin and border styles.
Conclusion
In this tutorial, you learned how to use ID selectors in CSS to target and style HTML elements based on their ID attributes. With this knowledge, you can apply unique styles to individual elements on your web page and create more precise designs.