DEV Community

Hemanath Kumar J
Hemanath Kumar J

Posted on

CSS - Flexbox - Complete Tutorial

CSS - Flexbox - Complete Tutorial

Introduction

Flexbox, a powerful layout tool in CSS, simplifies the design of complex layouts with flexible box model. It allows responsive adjustments to layouts with minimal code, making it a favorite among web developers. This tutorial aims to take you through the core concepts of Flexbox, backed by practical examples.

Prerequisites

  • Basic understanding of HTML and CSS
  • Code editor (VSCode, Sublime, etc.)
  • Modern web browser

Step-by-Step

1. Setting Up Your Environment

Create an HTML file and a CSS file. Link the CSS file to your HTML document in the <head> section.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Tutorial</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <!-- Flex items will go here -->
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. Basic Flex Container

In your CSS, start by defining a flex container. This turns direct children of that container into flex items.

.container {
    display: flex;
}
Enter fullscreen mode Exit fullscreen mode

3. Flex Direction

You can decide the main axis of your items using flex-direction. This can be row or column.

.container {
    display: flex;
    flex-direction: column;
}
Enter fullscreen mode Exit fullscreen mode

4. Justify Content

Adjust the alignment of flex items on the main axis (horizontal by default) using justify-content. This property has many values like center, flex-start, flex-end, space-between, and more.

.container {
    display: flex;
    justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

5. Align Items

To align items on the cross axis (vertical if your main axis is horizontal), use align-items.

.container {
    display: flex;
    align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Code Examples

  • Example of a navigation bar:
.navbar {
    display: flex;
    justify-content: space-between;
}
Enter fullscreen mode Exit fullscreen mode
  • Example of a sidebar layout:
.sidebar {
    display: flex;
    flex-direction: column;
    height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Use flex-wrap to handle multiple items in a container.
  • Apply flex-grow, flex-shrink, and flex-basis to control the flex items' size dynamically.
  • Test your layout in different browsers to ensure compatibility.

Conclusion

Flexbox is an essential tool for any web developer looking to create responsive and adaptable web layouts. Through practice and exploration, you can master its properties and create stunning web designs. Happy coding!

Top comments (0)