Getting Started with Flexbox

Tutorial 1 of 5

Getting Started with Flexbox

1. Introduction

In this tutorial, we aim to provide an introductory guide to CSS Flexbox, a powerful layout model which allows for flexible and efficient alignment, distribution and sizing of elements within a container.

By the end of this tutorial, you will learn:

  • What Flexbox is and why it is used
  • How to create a Flex container and control its properties
  • How to control the positioning and alignment of elements within a Flex container.

If you have a basic understanding of HTML and CSS, you're good to go.

2. Step-by-Step Guide

Understanding Flexbox

CSS Flexbox, or Flexible Box, is a layout model that allows you to control the alignment, direction, order, and size of boxes within a container, even when their sizes are unknown or dynamic. It's a great tool for building responsive designs.

Creating a Flex Container

To create a Flex container, you simply need to select an element and set its display property to flex.

.container {
  display: flex;
}

Any child elements of the .container will now become flex items.

Controlling the Flex Direction

By default, the flex items are displayed in a row, but you can change this using the flex-direction property.

.container {
  display: flex;
  flex-direction: column;
}

This will stack the flex items vertically.

3. Code Examples

Example 1: Basic Flexbox Layout

Here is a simple example of a Flexbox layout.

<div class="container">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
</div>
.container {
  display: flex;
}

.box {
  border: 1px solid black;
  padding: 10px;
}

The CSS above will horizontally align the three .box divs within the .container div.

Example 2: Using justify-content

The justify-content property aligns items along the main axis of the container.

.container {
  display: flex;
  justify-content: center;
}

This will center the flex items within the container.

4. Summary

In this tutorial, you have learned the basics of CSS Flexbox, including how to create a flex container, control the direction of flex items, and align them using justify-content.

To continue learning, you should experiment with other Flexbox properties, such as align-items, flex-wrap, and flex-grow.

5. Practice Exercises

  1. Create a Flex container and vertically stack its child elements.
  2. Center the child elements of a Flex container both vertically and horizontally.
  3. Create a Flex container that wraps its child elements into a new row or column when they overflow.

You can check your solutions and get more practice with the Flexbox Froggy game. Happy coding!