Adding CSS to HTML
๐ Covered in this chapter:
Inline CSS ยท Internal CSS ยท External CSS ยท link element ยท Multiple Stylesheets ยท @import ยท media ยท Loading Order ยท Common Mistakes
Welcome to Chapter 2: Adding CSS to HTML โ part of the CSS Complete Roadmap. This lesson covers all subtopics with clear explanations, code examples, and best practices used in professional web development.
1Three Ways to Add CSS
| Method | Syntax | Best For |
|---|---|---|
| Inline CSS | style="..." attribute on element | Quick one-off tests (avoid in production) |
| Internal CSS | <style> in <head> | Single-page demos, email templates |
| External CSS | <link rel="stylesheet"> | Production websites (recommended) |
2Inline CSS
HTML element meedha direct ga style attribute add chestam:
HTML โ Inline CSSโถ Try in Editor
<p style="color: red; font-size: 18px;">Inline styled paragraph</p>
Drawbacks: Reuse cheyadam kashtam, specificity highest (override cheyadam hard), HTML and CSS mix avuthundi โ maintainability poor.
3Internal CSS (<style> tag)
HTML โ Internal CSSโถ Try in Editor
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Internal CSS Demo</title>
<style>
body { background-color: #f5f5f5; font-family: sans-serif; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>Hello CSS</h1>
</body>
</html>
4External CSS โ <link> Element (Recommended)
Production lo separate .css file create chesi HTML lo link chestam. Browser cache chesi performance improve avuthundi.
HTML โ External Stylesheet Linkโถ Try in Editor
<link rel="stylesheet" href="styles.css">
CSS โ styles.cssโถ Try in Editor
body {
background-color: #f5f5f5;
font-family: 'Inter', sans-serif;
margin: 0;
line-height: 1.6;
}
CSS file structure best practice:
project/ โโโ index.html โโโ css/ โ โโโ main.css โ primary styles โ โโโ components.css โ โโโ utilities.css โโโ assets/
5Multiple Stylesheets, @import & media Attribute
Multiple CSS files link cheyochu โ order matters (later rules override earlier ones if specificity same):
HTML โ Multiple Stylesheets
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="layout.css">
<link rel="stylesheet" href="theme.css">
@import (CSS file lo inkoka CSS import):
CSS โ @import
@import url('typography.css');
@import url('components.css');
media attribute โ conditional loading (print styles, dark mode, responsive):
HTML โ media attribute
<link rel="stylesheet" href="print.css" media="print">
<link rel="stylesheet" href="mobile.css" media="(max-width: 768px)">
6CSS Loading Order & Common Mistakes
Loading order priority: Browser stylesheet โ User stylesheet โ Author stylesheet (external + internal + inline, by specificity and order).
โ ๏ธ Common Linking Mistakes
- Wrong file path in
hrefโ styles load avvavu rel="stylesheet"missing โ browser CSS ga treat cheyadu<link>ni<body>lo pettadam โ render blocking, FOUC- Same selector multiple files lo โ confusion; use consistent architecture