Creating and Running .css Files
This page explains how to save CSS styles as a text file and apply them to a web page. The file itself is simply a plain text file saved with a .css extension.
How to write a .css file
Write your CSS styles in a text editor and save the file with a .css extension. Save the file using the UTF-8 character encoding.
style.css
body {
font-family: sans-serif;
background-color: #f5f5f5;
color: #333;
}
h1 {
font-size: 24px;
color: #0066cc;
}
p {
line-height: 1.8;
}
As shown, you write styles using selectors and curly braces ({ }). Multiple styles can be written together in a single file.
How to write comments
You can write comments (notes) in a .css file. Comments are ignored by the browser, so they are useful for leaving descriptions or notes about the styles. CSS does not have single-line comments (//); only multi-line comments (/* */) can be used.
| Syntax | Description |
|---|---|
| /* comment */ | A comment. Can be used for a single line or multiple lines. Everything from /* to */ is a comment. |
/* ========== Global reset ========== */
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
/* Heading styles. */
h1 {
font-size: 24px;
color: #0066cc; /* Specifies blue. */
}
/*
The following are paragraph styles.
Line height is set to be wider than the default.
*/
p {
line-height: 1.8;
}
Adding separator comments like /* ===== Title ===== */ at section breaks helps keep large CSS files organized and readable.
How to run (load from HTML)
Opening a CSS file on its own in a browser has no effect. Write a <link> tag in the <head> section of an HTML file to load the CSS file, then open the HTML file in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample</title>
<link rel="stylesheet" href="style.css?lang=en">
</head>
<body>
<h1>Heading</h1>
<p>Paragraph text.</p>
</body>
</html>
Use <link rel="stylesheet" href="filename.css?lang=en"> to load the .css file. If index.html and style.css are in the same folder, you can specify just the filename.
Open index.html in a browser and the page will be displayed with the CSS styles applied. To check style changes, save the CSS file and then reload the browser (F5 or Ctrl + R).
If you want to inspect styles in detail, open the browser developer tools (Windows: F12, macOS: Command + Option + I), select an element, and you can view and edit the applied styles.
Summary
A .css file is simply a plain text file. You can create one by writing CSS styles in a text editor and saving it with a .css extension. No special tools are needed.
A CSS file is loaded with an HTML <link> tag. Because a single .css file can be shared by multiple HTML files, it is useful for managing the design of an entire site from one place.
Comments use /* */ only; single-line comments (//) are not available in CSS.
For recommended editors, see Setup.
If you find any errors or copyright issues, please contact us.