Beginner's Guide to CSS: Boost Your Website's Style

Beginner's Guide to CSS: Boost Your Website's Style

Learning and Documentating CSS

What is CSS?

CSS (Cascading Style Sheets) is the language used to style and design web pages. The term "cascading" means that styles applied to parent elements cascade down to child elements unless overridden.

At its core, CSS involves two key actions:

  1. Selecting elements on a webpage.

  2. Styling those elements based on the selection.

Inline Styling

Inline styling is applied directly within the HTML element:

<h1 style="color: blue;">Lorem ipsum dolor sit. </h1>

Here, the style attribute specifies the styling directly within the line of code.

Page Styling (Internal CSS)

Add a <style> tag inside the <head> to define styles for the entire page:

<head>
<style>
h2 {
    color: blue;
  }
</style>
</head>

Using Classes and IDs:

  • Classes: Used for multiple elements, selected using a dot (.).

  • IDs: Unique to a single element, selected using a hash (#).

.exampleclass { 
color: red;
}
#exampleid { 
font-size: 20px;
}

External CSS

Create a separate .css file for styling and link it to your HTML file:

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

Box Model

The box model determines how much space an element occupies:

  • Content: Actual content of the element.

  • Padding: Space between content and border.

  • Border: Surrounds the padding.

  • Margin: Space outside the border, separating elements.

Example:

{ 
margin: 0; 
padding: 0; 
box-sizing: border-box; 
}
  • content-box: Default behavior where padding and border are added to content width.

  • border-box: Includes padding and border within the total width.

Flexbox

Flexbox provides powerful layout control for aligning and positioning elements.

Basic Syntax:

display: flex;
justify-content: center;
align-items: center;

Key Properties:

  • justify-content: Aligns items along the main axis (left to right) (e.g., center, space-around).

  • align-items: Aligns items along the cross axis (or) another axis (top to bottom) (e.g., center).

  • flex-wrap: Controls whether items wrap to the next line.

Grid Layout

CSS Grid enables precise control over rows and columns.

Example:

display: grid;
grid-template-columns: 1fr 2fr 1fr; /* Defines three columns */
gap: 20px; /* Adds space between grid items */

Control inner elements using grid-column and grid-row:

grid-column: 1 / 3; /* Spans from column 1 to 3 */
grid-row: 1 / 2; /* Spans from row 1 to 2 */

Media Queries

Use media queries to make styles responsive:

@media (min-width: 600px) and (max-width: 900px) {
  body {
    background-color: lightblue;
  }
}

Selectors Overview

  • Universal Selector: * {} (Applies to all elements)

  • Type Selector: h1, p {} (Targets specific elements)

  • Class Selector: .classname {}

  • ID Selector: #id {}

  • Pseudo-classes: a:hover {} (Styling on user action)

  • Pseudo-elements: p::first-letter {}