dsds The CSS id selector targets an HTML element with a unique id.
Id selector syntax:
#id-name {
property-name: value;
}
Here’s an HTML element with that same id name as an attribute value:
<div id="id-name"></div>
The CSS id selector #id-name
is attached to the <div>
element with the id-name
attribute. That means that whatever styling properties you add to .id-name
in your CSS stylesheet get applied to the <div>
.
The hash symbol (#
) before the name of the id is a specific CSS syntax. When you add the id name to an HTML element as an id attribute you don’t use the #
symbol.
Now let’s use what we just learned in a practical example.
Here’s an HTML <button>
element with some default styling that is inherited from the browser’s User Agent Stylesheet:
<button>Button</button>
Default look:
Boring huh?
Let’s override the default button styling by creating a CSS id called #my-button
and give it some styling properties:
#my-button {
font-size: 18px;
padding: 14px 24px;
border-radius: 8px;
border: none;
background-color: #F7575C;
color: white;
}
And then add the id to the button element as an id attribute:
<button id="my-button">Button</button>
Result:
The most important thing to know abou the id selector is that unlike CSS class selectors ids can only be applied to one element on a page. This makes ids less flexible to use than classes, but also more predictable.
The rule of thumb is to only use ids for single elements that appear once on a page, such as a header, footer, or navigation bar.