CSS Basics

Learn how to style your website with simple CSS.

Introduction to CSS

CSS (Cascading Style Sheets) is the language used to style HTML elements on your web pages. While HTML provides the structure and content, CSS controls the visual appearance - colors, fonts, layout, spacing, and more. With CSS, you can transform a plain HTML document into a visually appealing website without needing to learn complex programming.

What You'll Need

  • Basic knowledge of HTML (see our Creating Your First Web Page guide)
  • A text editor (Notepad++, Visual Studio Code, or even basic Notepad)
  • A web browser to view your results

CSS Fundamentals

How CSS Works

CSS works by selecting HTML elements and applying styles to them. The basic structure of CSS involves:

selector {
    property: value;
    another-property: another-value;
}
  • Selector: Targets the HTML element(s) you want to style
  • Property: The style attribute you want to change (like color, font-size, etc.)
  • Value: The setting you want to apply to the property

Example CSS Rule

p {
    color: blue;
    font-size: 16px;
    line-height: 1.5;
}

This CSS rule selects all paragraph elements (<p>) and makes the text blue, sets the font size to 16 pixels, and sets the line height to 1.5 times the font size.

3 Ways to Add CSS to HTML

There are three methods to add CSS to your web pages:

1. External CSS (Recommended)

Create a separate CSS file and link it to your HTML documents:

  1. Create a file named styles.css
  2. Add your CSS rules to this file
  3. Link the CSS file in the <head> section of your HTML:
<!-- In your HTML file -->
<head>
    <link rel="stylesheet" href="styles.css">
</head>

Why External CSS is Best

External CSS files allow you to use the same styles across multiple pages. When you update the CSS file, all linked pages will reflect the changes, making maintenance much easier.

2. Internal CSS (Embedded)

Add CSS rules directly in the <head> section of an HTML document:

<!-- In your HTML file -->
<head>
    <style>
        p {
            color: blue;
            font-size: 16px;
        }
        h1 {
            color: red;
            font-family: Arial, sans-serif;
        }
    </style>
</head>

This method is useful for single-page websites or when you need page-specific styles.

3. Inline CSS

Apply CSS directly to individual HTML elements using the style attribute:

<p style="color: blue; font-size: 16px;">This paragraph is blue with 16px font size.</p>

Inline CSS should be used sparingly, mainly for one-off style changes or testing.

CSS Priority

When styles conflict, inline CSS takes priority over internal CSS, which takes priority over external CSS. More specific selectors also take priority over less specific ones.

CSS Selectors

Selectors are patterns used to select and style HTML elements. Here are the most common types:

Selector Type Example What It Selects
Element Selector p { } All <p> elements
Class Selector .intro { } All elements with class="intro"
ID Selector #header { } The element with id="header"
Descendant Selector article p { } All <p> elements inside <article> elements
Direct Child ul > li { } All <li> elements that are direct children of <ul>
Attribute Selector a[target="_blank"] { } All <a> elements with target="_blank"
Pseudo-class a:hover { } <a> elements when the mouse hovers over them

Classes vs. IDs

  • Classes (.classname) can be reused on multiple elements and an element can have multiple classes
  • IDs (#idname) should be unique to a single element on a page

Using Classes and IDs in HTML

<!-- HTML with class and ID -->
<div id="main-content">
    <p class="intro highlight">This paragraph has two classes.</p>
    <p class="intro">This paragraph has one class.</p>
</div>

<!-- CSS -->
#main-content {
    background-color: #f0f0f0;
    padding: 20px;
}

.intro {
    font-size: 18px;
    line-height: 1.6;
}

.highlight {
    background-color: yellow;
}

Essential CSS Properties

Let's cover the most commonly used CSS properties you'll need:

Text Styling

p {
    color: #333333;              /* Text color (hexadecimal) */
    font-family: Arial, sans-serif; /* Font type with fallbacks */
    font-size: 16px;             /* Font size */
    font-weight: bold;           /* Font weight: normal, bold, 100-900 */
    text-align: center;          /* Alignment: left, right, center, justify */
    line-height: 1.5;            /* Line spacing */
    text-decoration: underline;  /* Underline, overline, line-through, none */
    text-transform: uppercase;   /* uppercase, lowercase, capitalize */
}

Colors and Backgrounds

div {
    /* Text color */
    color: red;                  /* Named color */
    color: #ff0000;              /* Hexadecimal (hex) */
    color: rgb(255, 0, 0);       /* RGB values */
    color: rgba(255, 0, 0, 0.5); /* RGB with alpha (transparency) */
    
    /* Background */
    background-color: #f0f0f0;   /* Background color */
    background-image: url('background.jpg'); /* Background image */
    background-repeat: no-repeat; /* no-repeat, repeat, repeat-x, repeat-y */
    background-position: center;  /* Position: top, right, bottom, left, center */
    background-size: cover;       /* Size: cover, contain, or specific values */
    
    /* Shorthand background property */
    background: #f0f0f0 url('background.jpg') no-repeat center / cover;
}

Box Model Properties

The CSS Box Model consists of content, padding, border, and margin:

CSS Box Model diagram showing content, padding, border, and margin

The CSS Box Model

div {
    /* Width and Height */
    width: 300px;               /* Width of the content area */
    height: 200px;              /* Height of the content area */
    max-width: 100%;            /* Maximum width */
    min-height: 150px;          /* Minimum height */
    
    /* Padding (inner space) */
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
    padding: 10px 20px;         /* Shorthand: top/bottom right/left */
    padding: 10px 20px 15px 25px; /* Shorthand: top right bottom left */
    
    /* Border */
    border-width: 2px;
    border-style: solid;        /* solid, dashed, dotted, double, etc. */
    border-color: #333;
    border: 2px solid #333;     /* Shorthand */
    border-radius: 5px;         /* Rounded corners */
    
    /* Margin (outer space) */
    margin-top: 20px;
    margin-right: 30px;
    margin-bottom: 20px;
    margin-left: 30px;
    margin: 20px 30px;          /* Shorthand: top/bottom right/left */
    margin: 20px 30px 25px 35px; /* Shorthand: top right bottom left */
}

Box-Sizing Property

By default, width and height only apply to the content area. To include padding and border in the width/height calculation, use:

* {
    box-sizing: border-box;
}

This makes layout calculations much easier and is commonly used in modern web development.

Layout Properties

div {
    /* Display Types */
    display: block;             /* block, inline, inline-block, flex, grid, none */
    
    /* Position */
    position: relative;         /* static, relative, absolute, fixed, sticky */
    top: 20px;                  /* Used with position (not static) */
    right: 30px;
    bottom: 20px;
    left: 30px;
    z-index: 10;                /* Stacking order (higher numbers appear on top) */
    
    /* Float */
    float: left;                /* left, right, none */
    clear: both;                /* both, left, right, none - used with float */
}

Modern Layouts with Flexbox

Flexbox is a modern CSS layout method that makes it easy to create responsive designs:

/* Parent container (flex container) */
.container {
    display: flex;             /* Enables flexbox */
    flex-direction: row;       /* row, column, row-reverse, column-reverse */
    justify-content: space-between; /* Horizontal alignment: flex-start, flex-end, center, space-around, space-between, space-evenly */
    align-items: center;       /* Vertical alignment: flex-start, flex-end, center, stretch, baseline */
    flex-wrap: wrap;           /* wrap, nowrap, wrap-reverse */
    gap: 20px;                 /* Space between flex items */
}

/* Child items (flex items) */
.item {
    flex: 1;                   /* Grow and shrink equally */
    /* Or more specific: */
    flex-grow: 1;              /* How much the item can grow */
    flex-shrink: 1;            /* How much the item can shrink */
    flex-basis: 200px;         /* Base size */
}

Simple Flexbox Example: 3-Column Layout

<!-- HTML -->
<div class="flex-container">
    <div class="flex-item">Column 1</div>
    <div class="flex-item">Column 2</div>
    <div class="flex-item">Column 3</div>
</div>

/* CSS */
.flex-container {
    display: flex;
    gap: 20px;
}

.flex-item {
    flex: 1;
    padding: 20px;
    background-color: #f0f0f0;
}

Responsive Design with Media Queries

Media queries allow you to apply different styles based on device characteristics, like screen width:

/* Base styles for all devices */
.container {
    width: 100%;
    padding: 20px;
}

/* Styles for screens wider than 768px */
@media screen and (min-width: 768px) {
    .container {
        width: 750px;
        margin: 0 auto;
    }
}

/* Styles for screens wider than 992px */
@media screen and (min-width: 992px) {
    .container {
        width: 970px;
    }
}

/* Styles for screens wider than 1200px */
@media screen and (min-width: 1200px) {
    .container {
        width: 1170px;
    }
}

Mobile-First Approach

It's a best practice to design for mobile devices first, then use media queries to enhance the layout for larger screens. This approach is known as "mobile-first" design.

Common Breakpoints

  • Small devices (phones): up to 576px
  • Medium devices (tablets): 577px to 768px
  • Large devices (desktops): 769px to 992px
  • Extra large devices: 993px and above

CSS for Common Website Tasks

Creating a Navigation Menu

<!-- HTML -->
<nav>
    <ul class="menu">
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="services.html">Services</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
</nav>

/* CSS */
.menu {
    list-style-type: none;
    margin: 0;
    padding: 0;
    display: flex;
    background-color: #333;
}

.menu li {
    margin: 0;
}

.menu a {
    display: block;
    color: white;
    text-decoration: none;
    padding: 15px 20px;
}

.menu a:hover {
    background-color: #555;
}

/* Responsive menu */
@media screen and (max-width: 600px) {
    .menu {
        flex-direction: column;
    }
}

Styling Buttons

.button {
    display: inline-block;
    padding: 10px 20px;
    background-color: #4CAF50;
    color: white;
    text-decoration: none;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
}

.button:hover {
    background-color: #45a049;
}

/* Button variants */
.button-secondary {
    background-color: #2196F3;
}

.button-secondary:hover {
    background-color: #0b7dda;
}

Creating a Grid of Cards

<!-- HTML -->
<div class="card-grid">
    <div class="card">
        <img src="image1.jpg" alt="Card image">
        <div class="card-content">
            <h3>Card Title</h3>
            <p>Card description goes here.</p>
        </div>
    </div>
    <div class="card">...</div>
    <div class="card">...</div>
    <div class="card">...</div>
</div>

/* CSS */
.card-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.card {
    flex: 1 0 300px; /* Grow, don't shrink, base width 300px */
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.card img {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.card-content {
    padding: 15px;
}

.card h3 {
    margin-top: 0;
}

CSS Best Practices

Organization

  • Group related styles together (e.g., typography, layout, colors)
  • Use consistent naming conventions for classes
  • Comment your CSS to explain complex parts
  • Consider using a CSS methodology like BEM (Block Element Modifier)

Performance

  • Minimize the use of overly specific selectors
  • Avoid using !important except as a last resort
  • Combine similar styles to reduce code repetition
  • Consider using CSS minification for production websites

Maintainability

  • Use variables for repeated values (with CSS custom properties)
  • Split large CSS files into multiple files by component or section
  • Avoid inline styles
  • Keep your stylesheets DRY (Don't Repeat Yourself)
/* Using CSS variables (custom properties) */
:root {
    --primary-color: #4CAF50;
    --secondary-color: #2196F3;
    --font-main: 'Arial', sans-serif;
    --spacing-unit: 8px;
}

.button {
    background-color: var(--primary-color);
    font-family: var(--font-main);
    padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
}

.header {
    color: var(--primary-color);
    font-family: var(--font-main);
    margin-bottom: calc(var(--spacing-unit) * 3);
}

CSS Tools and Resources

CSS Frameworks

CSS frameworks provide pre-designed components and layout systems:

  • Bootstrap - Popular framework with extensive components
  • Tailwind CSS - Utility-first approach to CSS
  • Bulma - Modern CSS framework based on Flexbox

CSS Tools

Browser Developer Tools

All modern browsers include developer tools that let you inspect and modify CSS in real-time:

  • Right-click on any element and select "Inspect" or "Inspect Element"
  • Use the Styles panel to see and modify CSS properties
  • Test responsive designs with the device emulation mode

Learning Trick

When you see a website with a design element you like, use browser developer tools to inspect it and see how it's created. This is a great way to learn new CSS techniques.

Next Steps

Now that you understand CSS basics, here are some ways to continue learning:

  • Practice styling your own website - Apply what you've learned to your HTML pages
  • Learn CSS animations - Add movement and interactivity to your website
  • Explore CSS Grid - Another powerful layout system that complements Flexbox
  • Try a CSS preprocessor like Sass or Less for more powerful styling capabilities
  • Learn JavaScript basics with our JavaScript Fundamentals guide to add interactivity to your styled pages

Need Help With CSS Styling?

Contact us for personalized assistance with website styling and design.

Get in Touch