CSS Basics

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

  1. Element Selectors:
    • Target HTML elements by their type.
    cssCopy codep { color: #000; }
  2. Class Selectors:
    • Target elements by their class attribute.
    cssCopy code.example { background-color: #D4D5D9; }
  3. ID Selectors:
    • Target elements by their ID attribute.
    cssCopy code#header { text-align: center; }

Common Properties

  1. Colors and Backgrounds:
    • color: Sets the text color.
    • background-color: Sets the background color.
    • background-image: Sets a background image.
  2. Fonts and Text:
    • font-family: Sets the font type.
    • font-size: Sets the font size.
    • text-align: Aligns text (left, right, center).
  3. 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:

  1. Embedded CSS:
    • CSS is included within the HTML document inside a <style> tag.
    htmlCopy code<style> body { background-color: #ACAD94; } </style>
  2. External CSS:
    • CSS is placed in a separate file and linked to the HTML document using a <link> tag.
    htmlCopy code<link rel="stylesheet" href="styles.css">
  3. Inline CSS:
    • CSS is written directly within an HTML element’s style attribute.
    htmlCopy code<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.