Introduction to CSS
Learn to style your web pages with cascading style sheets to control presentation, layout, and appearance.
What is CSS?
CSS, or Cascading Style Sheets, is the language used to describe the presentation of a web page written in a markup language like HTML. While HTML provides the content and structure of a page, CSS handles the visual aspects, such as colors, fonts, spacing, and layout.
By separating content from presentation, CSS makes it easier to manage and update the look of your website. A single CSS file can control the style of multiple HTML pages, ensuring a consistent design across your entire site.
đź’ˇ Analogy
If HTML is the skeletal structure of a house, CSS is the interior and exterior design—the paint colors, furniture arrangement, flooring, and landscaping that make it visually appealing.
The Three Ways to Add CSS
There are three main methods for applying CSS to your HTML document, each with its own use case and best practices.
This is the most common method. You define your CSS rules in a separate .css
file and link it to your HTML page using the <link>
element in the <head>
section. This is ideal for managing styles across an entire website.
<head> <link rel="stylesheet" href="styles.css"> </head>
With this method, you place your CSS rules directly inside a <style>
tag within the <head>
section of your HTML document. This is useful for single pages or when the styles are unique to that page.
<head> <style> h1 { color: blue; } </style> </head>
Inline styles are applied directly to an HTML element using the style
attribute. This approach is generally discouraged as it mixes content and presentation, making your code difficult to read and maintain.
<h1 style="color: blue;">Hello, World!</h1>
CSS Syntax
A CSS rule consists of a selector and a declaration block. The selector points to the HTML element you want to style. The declaration block contains one or more declarations separated by semicolons.
/* Selector */ p { /* Declaration: property and value */ font-size: 16px; line-height: 1.5; color: #333; }