CSS Syntax and Usage
Introduction
CSS (Cascading Style Sheets) is a fundamental part of web development, responsible for controlling the presentation and visual appearance of web pages. This article delves into the syntax and various ways to apply CSS styles.
External Stylesheet
An external stylesheet is a separate file with a .css extension that contains all your CSS rules. It is the most common and recommended approach for larger projects.
Creating an External Stylesheet:
/* style.css */
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
font-size: 2em;
}
Linking the Stylesheet:
<link rel="stylesheet" href="style.css">
Internal Stylesheet
An internal stylesheet is placed directly within the <head> section of your HTML document.
<head>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
font-size: 2em;
}
</style>
</head>
Inline Stylesheet
Inline styles are applied directly to HTML elements using the style attribute.
<h1 style="color: #333; font-size: 2em;">This is a Heading</h1>
Avoid This
Inline styles should be used sparingly as they can clutter your HTML code and make it harder to maintain.
Summary
- CSS syntax defines how to apply styles to HTML elements.
- External stylesheets provide a structured and organized way to manage styles.
- Internal stylesheets are suitable for smaller styles that apply only to a specific document.
- Inline styles are best used for minor adjustments and should be avoided for larger styles.
- Comments help explain and document your CSS code.
Comments
Comments are used to add explanations or notes within your CSS code. They are ignored by browsers.