
What Is CSS? An Introduction to Cascading Style Sheets
10/10/2019
CSS Selectors: Types, Combinators, and Examples
11/10/2019
2. Applying CSS to an HTML document
You can add CSS inline, in a style element, or in a separate stylesheet. All three examples make a paragraph green. The difference is where the rule lives and how widely you can reuse it.
2.1. Inline CSS
Put CSS declarations in the element’s style attribute. They affect that element directly. Inline styling becomes hard to maintain when many elements need the same look, because each must be edited separately. Mixing styles into the markup also makes the HTML harder to read.
<p style="color: green;">A green paragraph.</p>Try the original inline example in CodePen.
2.2. Internal CSS
Add a <style> element inside the document’s <head>. Its rules can apply to any matching element on the page. This is useful for a standalone page or when your content management system gives you limited access to stylesheets. If you copy the same rules across pages, you’ll have to update each copy.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Internal CSS example</title>
<style>
p { color: green; }
</style>
</head>
<body>
<p>A green paragraph.</p>
</body>
</html>Try the original internal stylesheet example in CodePen.
2.3. External CSS
Save the rules in a separate .css file and load it with <link rel="stylesheet"> in the HTML head. Several pages can share the same stylesheet, so one edit can update them all.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>External CSS example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>A green paragraph.</p>
</body>
</html>styles.css
p { color: green; }Try the original external CSS example in CodePen. If the styles fail to load, check how the stylesheet path is resolved. You can also check your markup with the W3C validator and check your styles with the W3C CSS Validator. Validation helps catch errors, and browser testing helps confirm that your layout works across browsers. See CSS best practices for further guidance on code quality and accessibility.
Try it yourself
Two pages share a stylesheet. Where should you change the paragraph color so both pages update?
Show the answer
Edit the p rule in the shared CSS file. Both pages must load it through their <link> element.