Chapter 3: CSS Fundamentals
Chapter 3: CSS Fundamentals
CSS (Cascading Style Sheets) is used to add style to HTML, making web pages visually appealing. It allows you to control colors, fonts, layout, spacing, and much more. CSS works by selecting HTML elements and applying styling rules to them, enabling you to create consistent and attractive designs.
Adding CSS to Your HTML
There are several ways to apply CSS to your HTML document: inline styles, internal stylesheets, and external stylesheets. Each approach has its specific use cases and advantages.
<!-- Inline CSS -->
<p style="color: blue; font-size: 20px;">This text is styled with inline CSS.</p>
<!-- Internal CSS -->
<head>
<style>
p {
color: green;
font-size: 18px;
}
</style>
</head>
<!-- External CSS -->
<link rel="stylesheet" href="styles.css">
CSS Selectors
Selectors are used to target HTML elements to apply styles. Here are some of the most common CSS selectors:
/* Element Selector */
p {
color: blue;
}
/* Class Selector */
.intro {
font-size: 20px;
color: green;
}
/* ID Selector */
#main-title {
font-size: 24px;
color: red;
}
Basic CSS Properties
Here are a few fundamental CSS properties that will help you start styling your web pages:
/* Text Color and Font */
p {
color: #333;
font-family: Arial, sans-serif;
}
/* Background Color */
body {
background-color: #f4f4f4;
}
/* Padding and Margin */
.container {
padding: 20px;
margin: 10px;
}
/* Borders */
.box {
border: 1px solid #ccc;
border-radius: 5px;
}
Example: Styling a Simple Web Page
Let’s combine some of these basics to style a simple webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Page</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1 id="main-title">Welcome to My Styled Webpage</h1>
</header>
<section class="intro">
<p>This page is styled with CSS.</p>
</section>
<div class="box">
<p>This box has a border and padding.</p>
</div>
</body>
</html>
Experimenting with Your Own CSS
Now that you understand the basics of CSS, try creating your own styles. Experiment with different colors, fonts, margins, padding, and borders to see how they affect your webpage’s look and feel. CSS is flexible and gives you complete control over the visual presentation of your content.