Element selectors target HTML elements directly by their tag name. For example, this paragraph is styled using the p element selector.
div element selector.
The CSS code for element selectors looks like:
h1 {
color: blue;
text-align: center;
}
p {
font-family: Arial, sans-serif;
line-height: 1.5;
}
div {
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ddd;
}
ID selectors target unique elements with a specific ID attribute. IDs must be unique - you can only use each ID once per page.
#unique-element ID selector.
The CSS code for ID selectors looks like:
#unique-element {
background-color: #ffeb3b;
font-weight: bold;
padding: 15px;
border: 2px dashed black;
}
#special-heading {
color: purple;
font-style: italic;
text-shadow: 1px 1px 2px #aaa;
}
Class selectors target elements with a specific class attribute. Multiple elements can share the same class.
This paragraph has class="highlight" and is styled using the .highlight class selector.
.box class selector.
This is another paragraph with class="highlight" - both get the same styling.
The CSS code for class selectors looks like:
.highlight {
background-color: #e6f7ff;
border-left: 4px solid #1890ff;
padding-left: 10px;
}
.box {
background-color: #f5f5f5;
border-radius: 5px;
padding: 15px;
}
.text-center {
text-align: center;
}
This paragraph has class="note" and is targeted by the p.note combined selector.
The CSS code for combined selectors looks like:
p.note {
font-style: italic;
color: #888;
font-size: 0.9em;
}
#container h2 {
color: green;
border-bottom: 1px solid green;
}
HTML elements can have multiple classes:
The HTML for multiple classes looks like:
<div class="box highlight">...</div>
When multiple rules apply to the same element, specificity determines which one wins:
A more specific selector will override a less specific one for the same property.