CSS Anatomy: The Core Syntax
Mastering CSS begins with understanding its structure. The syntax is the set of rules that tells the browser exactly what you want it to do with your HTML elements. It's a simple, yet incredibly powerful language grammar.
The Rule Structure
Every piece of styling you write in CSS is part of a Ruleset (or Rule). A ruleset consists of two primary components: the Selector and the Declaration Block.
The Selector
The selector points to the HTML element you want to style. It "selects" the targets.
- Type Selectors: Target elements by their HTML tag name (e.g.,
p,h1,div). - Class Selectors: Target elements with a specific class attribute. Always start with a period (e.g.,
.button). - ID Selectors: Target a single, unique element on the page. Always start with a hash (e.g.,
#header).
Declarations (Properties & Values)
Inside the curly braces { } lives the declaration block. Here, you write one or more declarations. Each declaration specifies a property you want to change, and the value you want to give it.
color: blue;
β PropertyΒ Β Β β Value
Punctuation is critical: The property and value are separated by a colon (:). Each declaration MUST end with a semicolon (;). Forgetting the semicolon is the #1 cause of broken CSS layouts for beginners!
β Frequently Asked Questions (Syntax)
What happens if I forget the semicolon (;) at the end of a declaration?
If you forget the semicolon and have more declarations below, the browser won't know where one rule ends and the next begins. This will break both the current line and the next one. Always use the semicolon!
Why use classes (.) instead of IDs (#)?
Classes are designed to be reusable. You can apply .btn to fifty different buttons on your page.IDs must be unique (only one #navbar per page). Plus, classes keep your CSS cleaner and more modular.
Is CSS case-sensitive?
In general, CSS property names and values (like color or blue) are not case-sensitive. HOWEVER, Class and ID names that link your HTML to your CSS are case-sensitive. (.MyClass is not the same as .myclass).
