Class and ID selectors
Learn the difference between .class and #id selectors.
Class selector
A class selector lets you tell apart elements of the same tag type. You write it as a dot followed by the class name. The .featured selector matches any element carrying the class="featured" attribute, whatever the tag.
One element can carry several class names: class="featured highlight". Both class selectors will match it. That makes classes ideal for reusable styles.
ID selector
An ID selector (#) targets a single element on the page. You write it as a hash followed by the id name. The #header selector matches the element carrying id="header".
HTML rules say an id must appear only once per page. That makes id selectors right for one-of-a-kind elements; for repeating styles, use a class.
Specificity order
When two selectors style the same element for the same property, specificity decides which wins. The simple order: an id selector beats a class selector, and a class selector beats a type selector.
So #main beats .box, and .box beats div. When two selectors of the same level clash, the one written later in the file wins.
Exercise Write class and id selectors
Add two separate style blocks. First a .button class selector carrying background: navy and color: white. Second a #main id selector carrying padding: 1rem.
Show example solution
/* add class and id selectors */
.button {
background: navy;
color: white;
}
#main {
padding: 1rem;
}
Test yourself
-
Which element matches the .menu class selector?
.menu { padding: 0.5rem; }- <nav id="menu">
- <menu>
- <ul class="menu">
- <ul class="navigation">
Show answer
<ul class="menu"> — Correct. The .menu class selector finds elements with class="menu"; <ul class="menu"> matches.
-
Write the id selector
____ { background: navy; color: white; }Show answer
#header { background: navy; color: white; }