Rules
A CSS rule consists of a selector and a declaration. The selector identifies the HTML element to style, while the declaration specifies the style properties.
cssCopy codeh1 {
color: #384d48;
font-size: 24px;
}
In the example above, h1
is the selector, and color
and font-size
are the declarations.
Types of Selectors
- Element Selectors:
- Target HTML elements by their type.
p { color: #000; }
- Class Selectors:
- Target elements by their class attribute.
.example { background-color: #D4D5D9; }
- ID Selectors:
- Target elements by their ID attribute.
#header { text-align: center; }
Common Properties
- Colors and Backgrounds:
color
: Sets the text color.background-color
: Sets the background color.background-image
: Sets a background image.
- Fonts and Text:
font-family
: Sets the font type.font-size
: Sets the font size.text-align
: Aligns text (left, right, center).
- Layouts:
margin
: Sets the outer space of elements.padding
: Sets the inner space of elements.border
: Sets the border of elements.
Designing a Website with CSS
Adding CSS to HTML
There are three ways to add CSS to an HTML document:
- Embedded CSS:
- CSS is included within the HTML document inside a
<style>
tag.
<style> body { background-color: #ACAD94; } </style>
- CSS is included within the HTML document inside a
- External CSS:
- CSS is placed in a separate file and linked to the HTML document using a
<link>
tag.
<link rel="stylesheet" href="styles.css">
- CSS is placed in a separate file and linked to the HTML document using a
- Inline CSS:
- CSS is written directly within an HTML element’s style attribute.
<p style="color: #8B8149;">This is a colored text.</p>
Practical Example
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header id="header">
<h1>Welcome to My Website</h1>
</header>
<section class="content">
<p>This is an example of how to use CSS to style text and elements.</p>
</section>
</body>
</html>
/* styles.css */
body {
background-color: #D4D5D9;
font-family: 'Arial', sans-serif;
}
#header {
background-color: #384d48;
color: #fff;
text-align: center;
padding: 20px;
}
.content {
margin: 20px;
padding: 20px;
background-color: #ACAD94;
}
p {
color: #8B8149;
font-size: 18px;
}
Conclusion
CSS is a powerful and essential tool for designing and styling web pages. By using CSS, you can create responsive and visually appealing websites easily. We hope this article has helped you understand the basics and key concepts of CSS and how to use it to enhance your web design.