CSS Introduction

CSS (Cascading Style Sheets) is the language used to control the presentation and layout of your web pages. It allows you to separate content (HTML) from style (CSS), making it easier to create visually appealing and consistent websites.

Structure of a CSS rule

A CSS rule consists of a selector, a property, and a value.

selector {
  property: value;
}
  • Selector: Defines which HTML element the style will be applied to (e.g., a paragraph, a heading, or a div).
  • Property: Defines which aspect of the element will be modified (e.g., color, font size, or margin).
  • Value: Defines the value of the property (e.g., «red», «16px», or «10px»).

Basic CSS selectors

  • Element selector: Selects all elements of a specific type (e.g., p, h1, div).
  • Class selector: Selects elements with a specific class (e.g., .highlight).
  • ID selector: Selects an element with a specific ID (e.g., #my-form).

Essential CSS properties and values

  • color: Defines the text color.
    • Values: color names (red, blue, green), hexadecimal values (#FF0000), RGB values (rgb(255, 0, 0)).
  • font-size: Defines the font size.
    • Values: pixels (px), em, rem.
  • background-color: Defines the background color.
    • Values: similar to color.
  • margin: Defines the margin around an element.
    • Values: pixels (px), em, rem, auto.
  • padding: Defines the padding space within an element.
    • Values: similar to margin.
  • border: Defines the border around an element.
    • Values: size, type, and color. Example: 1px solid black.
  • text-align: Defines the text alignment.
    • Values: left, right, center, justify.
  • width and height: Define the width and height of elements.
    • Values: pixels (px), percentages (%).

How to include CSS in your HTML

Inline CSS: Applied directly to an HTML element using the style attribute.

<p style="color: blue;">This paragraph is blue.</p>

Internal CSS: Included within the <style> tag in the <head> section of the HTML document.

<head>
  <style>
    p {
      color: green;
    }
  </style>
</head>

External CSS: A separate CSS file is created and linked to the HTML document using the <link> tag.

<head>
  <link rel="stylesheet" href="styles.css">
</head>

Practical examples

/* Styles for all paragraphs */
p {
  font-size: 16px;
  color: #333;
}

/* Styles for elements with the class "highlight" */
.highlight {
  background-color: yellow;
  padding: 10px;
}

/* Styles for the element with the ID "my-form" */
#my-form {
  border: 1px solid #ccc;
  margin-top: 20px;
}