Web Development - CSS Introduction
What is CSS?
CSS stands for Cascading Style Sheets.
It describes how HTML elements should look when displayed in the browser.
While HTML structures the content, CSS makes it beautiful:
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p {
font-family: Arial;
color: darkblue;
}
</style>
</head>
<body>
<h1>Welcome to My Page</h1>
<p>This page is styled with CSS!</p>
</body>
</html>
Try it Yourself »
Why Use CSS?
- CSS saves time - you can style multiple pages with one stylesheet.
- CSS improves consistency and maintainability.
- CSS separates content (HTML) from presentation (style).
- CSS makes websites look modern and responsive.
Tip: Use CSS to define colors, fonts, and spacing once, and reuse those styles everywhere.
How to Add CSS
There are three ways to apply CSS to your web pages:
- Inline CSS - inside an HTML element
- Internal CSS - inside a <style> element in the <head>
- External CSS - in a separate .css file
1. Inline CSS
Inline CSS is written directly inside an element's style attribute.
Example
Inline CSS:
<h1 style='color:blue; text-align:center;'>This is a heading</h1>
<p style='color:gray;'>This is a paragraph.</p>
Try it Yourself »
2. Internal CSS
Internal CSS is placed inside a <style> element in the <head> section.
Example
Internal CSS:
<style>
body {
background-color: lightyellow;
}
h1 {
color: darkgreen;
}
p {
font-size: 18px;
}
</style>
Try it Yourself »
3. External CSS
External CSS is written in a separate file with a .css extension, and linked using the <link> tag.
Example
External CSS file:
<link rel='stylesheet' href='styles.css'>
styles.css file:
body {
background-color: lightgray;
}
h1 {
color: navy;
}
p {
color: black;
}
Try it Yourself »
Tip: External CSS is the best choice for large projects. You can reuse the same stylesheet across many pages.
CSS Syntax
A CSS rule consists of a selector and one or more declarations.
Example
CSS syntax:
selector {
property: value;
}
Example:
p {
color: red;
text-align: center;
}
This CSS rule will make all paragraphs red and centered.
Selectors in CSS
- Element selector: targets HTML tags (
p,h1). - Class selector: uses a dot (
.), e.g..intro. - ID selector: uses a hash (
#), e.g.#header.
Example
Different selectors:
p {
color: blue;
}
.intro {
font-size: 18px;
}
#main {
text-align: center;
}
Try it Yourself »
Best Practices
- Use external stylesheets for consistency and scalability.
- Keep CSS clean and well-commented.
- Use class selectors instead of inline styles for reusable code.
- Organize styles logically (layout, typography, colors, etc.).
Summary
- CSS styles how HTML looks.
- Can be added inline, internal, or external.
- CSS syntax uses selectors and declarations.
- External CSS is preferred for large projects.
Next, you'll learn more about CSS Syntax - the basic rules that make CSS work.