CSS How To
How To Add CSS
There are three main ways to add CSS to a web page: external CSS, internal CSS, and inline CSS. The most common and recommended method is external CSS because it keeps styles reusable and easy to maintain.
- External CSS (recommended): styles are stored in a separate
.cssfile - Internal CSS: styles are written inside a
<style>tag in the HTML - Inline CSS: styles are added directly to an element using the
styleattribute
External CSS
With external CSS, you place your styles in a separate file and link it from your HTML. This is the best approach for most websites because one CSS file can style multiple pages.
<!-- index.html --> <head> <link rel="stylesheet" href="styles.css"> </head>
/* styles.css */
body {
font-family: Arial, sans-serif;
}
h1 {
color: #1f4bd8;
}
Add Internal CSS
Internal CSS is written inside a <style> tag in the HTML document. It can be useful for single-page demos or quick tests, but it is not ideal for larger sites.
<head>
<style>
body { font-family: Arial, sans-serif; }
p { color: #333; }
</style>
</head>
Add Inline Style
Inline CSS is added directly to an element using the style attribute. It has the highest priority among these three methods, but it is hard to maintain and should be used sparingly.
<p style="color: green; font-weight: bold;"> This paragraph uses inline CSS. </p>
Which Method Should You Use?
- Use external CSS for real projects and multi-page websites
- Use internal CSS for small demos or a single page
- Use inline CSS only for quick overrides or special cases
Multiple Style Sheets
You can link multiple CSS files to the same HTML page. The browser loads them from top to bottom, and if two rules have the same specificity, the last one wins.
<head> <link rel="stylesheet" href="base.css"> <link rel="stylesheet" href="theme.css"> </head>
In this setup:
base.csscontains common styles shared across the sitetheme.csscontains theme colors or page-specific overrides
Order Matters
If two rules target the same element with the same selector strength, the last loaded stylesheet will override the earlier one.
/* base.css */
p { color: #333; }
/* theme.css */
p { color: #1f4bd8; }
Because theme.css is loaded after base.css, paragraph text becomes blue.
Code Challenge
Goal: Add CSS to style the page below. Use external CSS (recommended) and make the heading blue and the box look like a card.
HTML:
<!-- index.html -->
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="card">
<h2>Profile</h2>
<p>This is a simple card layout.</p>
</div>
</body>
Task:
- Set the page font to Arial
- Make the
h2text blue - Give
.cardpadding, a border, and rounded corners
Try a Solution (styles.css):
body {
font-family: Arial, sans-serif;
}
h2 {
color: #1f4bd8;
margin-top: 0;
}
.card {
padding: 16px;
border: 1px solid #ddd;
border-radius: 10px;
max-width: 420px;
}
What’s Next?
Next, you will learn how to write CSS comments and keep your styles easy to read and maintain.