CSS Introduction: Painting the Web
If HTML is the skeleton and structure of a house, CSS is the paint, the furniture layout, and the interior design. Without CSS, the web would just be black-and-white text on a white screen.
What is CSS?
CSS stands for Cascading Style Sheets. It was proposed in 1994 by HΓ₯kon Wium Lie to separate the content (HTML) from the presentation (visual design). This separation allows developers to style multiple pages with a single file.
The Building Blocks: Syntax
A CSS rule consists of a Selector and a Declaration Block. Inside the block, you write declarations, which are key-value pairs separated by a colon and ending with a semicolon.
- Selector: Points to the HTML element you want to style (e.g.,
p,.my-class,#header). - Property: The aspect of the element you want to change (e.g.,
color,font-size). - Value: The specific setting you want to apply (e.g.,
blue,16px).
The Cascade and Specificity
The "Cascading" part of CSS means that styles fall from top to bottom. If you write two rules targeting the exact same element with the exact same specificity, the last one written wins.
However, Specificity overrides the cascade. An ID selector (#) is more specific than a Class selector (.), and a Class is more specific than an Element tag (like h1). Understanding this hierarchy is the key to preventing "CSS headaches".
View Best Practices+
Keep styles external! Use the <link rel="stylesheet" href="style.css"> tag in your HTML head. Avoid using inline styles (style="...") unless absolutely necessary, as they break the separation of concerns and are notoriously hard to override.
β Frequently Asked Questions
What does CSS stand for and what is it used for?
CSS (Cascading Style Sheets) is the language used to describe the presentation of a document written in HTML. It is used to add color, fonts, layout, and animations to web pages.
What is the difference between a class (.class) and an ID (#id)?
Classes (.class): These can be used multiple times on the same page. They are ideal for reusable styles like buttons or cards.
IDs (#id): These must be unique; there can only be one element with a specific ID per page. They have higher weight (specificity) than classes when applying styles.
/* Class - reusable */ .red-button { background: red; }/* ID - unique */ #main-header { border-bottom: 2px solid black; }What is the "Cascade" in CSS?
The cascade is the algorithm that determines which CSS rule applies to an element if there are conflicts. It depends on 3 main factors: importance (e.g., `!important`), specificity (ID vs. Classes), and source order (whatever is lower in the file overwrites what is above it).
