Understanding CSS syntax and selectors
CSS syntax and selectors. How you tell the browser which elements to style and what to change. Get these right and the rest of CSS becomes much easier.
CSS syntax
Every CSS rule follows the same pattern: a selector, then a block of declarations.
selector {
property: value;
}
- Selector: the HTML element you want to style – e.g.
body,h1, orp. - Property: the attribute to change – e.g.
color,font-size, ormargin. - Value: what you want that property set to.
To make all paragraphs blue:
p {
color: blue;
}
Short, readable, and enough to style most of a page once you know your selectors.
Selectors
Selectors choose which elements a rule applies to. The main types:
- Type selector: targets elements by tag name (e.g.
h1,p,div). - Class selector: targets elements with a given class. Starts with a full stop (e.g.
.classname). - ID selector: targets one element with a given id. Starts with a hash (e.g.
#header). - Attribute selector: targets elements by attribute and value (e.g.
input[type='text']). - Pseudo-class selector: targets a state (e.g.
:hover,:focus). - Pseudo-element selector: targets part of an element (e.g.
::first-line,::after). - Descendant selector: targets nested elements (e.g.
div p). - Child selector: like descendant, but only direct children (e.g.
ul > li). - Adjacent sibling selector: targets the element immediately after another (e.g.
h1 + p). - General sibling selector: targets all following siblings (e.g.
h1 ~ p).
Each type gives you a different level of precision.
Selectors in practice
Take this HTML:
<div id="container">
<h1 class="title">Welcome to My Blog</h1>
<p>This is a <span>special</span> paragraph.</p>
<p class="highlight">Highlighted Text</p>
</div>
- Type selector:
p {
color: #333;
}
- Class selector:
.highlight {
background-color: yellow;
}
- ID selector:
#container {
margin: 20px;
}
- Pseudo-class selector:
p:hover {
color: red;
}
- Child selector:
#container > p {
font-size: 18px;
}
Same HTML, different selectors, different results.
Combining selectors
You can chain selectors for tighter targeting. To style only paragraphs with class .highlight inside #container:
#container .highlight {
border: 1px solid blue;
}
Universal selector and specificity
The universal selector (*) matches every element. Use it sparingly.
When two rules conflict, specificity decides the winner. Inline styles beat ids, ids beat classes, classes beat type selectors. We cover the full scoring system in the article on the cascade.
Selectors are the main tool you reach for in CSS. The more you use them, the faster you will spot which rule is affecting which element.

