The CSS ID selector is indicated by the hash (#) symbol in the stylesheet. It matches the ID attribute of an HTML element on a page.
HTML
<div id="container">Your content</div>
From our stylesheet we can access it like this:
CSS
#container { background-colour: green; }
We can only use the same ID once in a document. It is used to select one unique element!
It’s best to avoid using IDs for css and only use the ID attribute in a document if you need to access that element via Javascript.
The CSS class selector selects one or more HTML elements with a class attribute.
HTML
<div class="alert">Your content</div>
To select the “alert” class in your stylesheet, we need to put a period (.) before the classname:
CSS
.alert {
margin-right: 10px;
}
You can use the same classname on multiple elements on a page. This way you can modify those elements at once. In the above example, every element that has the class “alert” will receive a margin-right 10px.
We can also add more than one class to an HTML element:
<div class="alert text-center">Your content</div>
In this case the classes must be separated by a space.
We can also narrow down which HTML element should be affected by a class:
div.alert {
background-colour: blue;
}
In this example, only divs using the class “alert” will have their background in blue. For example,
<p class="alert">Content</p>
will not be affected.
Leave a reply
You must be logged in to post a comment.