Learning Objectives
- Understand the core mechanics of how CSS interacts with HTML.
- Learn the fundamental syntax of a CSS rule.
- Discover the three methods for linking stylesheets to an HTML document.
- Grasp the concept of "the cascade" and how styles are prioritized.
CSS (Cascading Style Sheets) is the language that gives your web pages their visual design. If HTML is the skeleton of a webpage, CSS is the skin, clothing, and makeup. It dictates everything from colors and fonts to the complex layouts of modern applications.
A CSS rule is made up of two main parts: a selector and a declaration block.
h1 {
color: blue;
font-size: 24px;
}
- Selector: The HTML element you want to style (in this case,
h1). - Declaration Block: The curly braces
{}that contain all the styles for that selector. - Declaration: Each individual rule inside the block, consisting of a property (like
color) and a value (likeblue), separated by a colon and ending with a semicolon.
There are three ways to apply CSS to your HTML documents.
Inline styles are applied directly to a single HTML element using the style attribute.
<p style="color: red; text-align: center;">This is a red paragraph.</p>
Best Practice Warning
Using inline CSS is generally discouraged for larger projects because it mixes content with design, making your code extremely difficult to maintain.
Internal styles are written inside a <style> element, which is placed within the <head> section of an HTML document.
<head>
<style>
body {
background-color: linen;
}
</style>
</head>
This is the industry standard approach. You write all your CSS in a separate file (e.g., styles.css) and link it to your HTML file using the <link> tag.
The "Cascading" in CSS refers to the algorithm the browser uses to decide which rules apply when multiple conflicting rules target the exact same element. The cascade evaluates rules based on:
- Source Order: If two identical selectors try to style the same element, the one that appears last in the code wins.
- Specificity: More specific selectors override less specific ones (e.g., an ID selector will override a general element selector).
- Importance: Using the
!importantflag will override almost all other cascade rules.
Pro Tip on !important
Use !important sparingly! Relying on it too often indicates poor CSS architecture and makes your code much harder to debug in the future.