CSS Flexbox

The CSS Flexible Box Layout, or Flexbox, is a one-dimensional layout model that allows items to be aligned and distributed efficiently within a container. It is especially useful when the size of items is dynamic or unknown. Flexbox simplifies responsive design and adapts well to different screen sizes.

Key Topics

Flexbox Basics

Flexbox introduces the concept of a flex container and its flex items. A flex container is created by setting the display property to flex or inline-flex. Flex items are the direct children of the flex container, and they align based on the container’s properties.

Flexbox Features

  • Alignment: Align items vertically and horizontally within a container.
  • Ordering: Change the visual order of items without altering the HTML structure.
  • Flexible Sizing: Items can grow, shrink, or remain fixed depending on available space.
  • Direction Control: Arrange items in rows or columns with wrapping options.

Basic Example

This example demonstrates the use of display: flex; to arrange items in a row.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Example</title>
    <style>
        .flex-container {
            display: flex;
            background-color: #F0F0F0;
            padding: 10px;
        }
        .flex-item {
            background-color: #007BFF;
            color: white;
            margin: 5px;
            padding: 20px;
            text-align: center;
            flex: 1;
        }
    </style>
</head>
<body>
    <div class="flex-container">
        <div class="flex-item">Item 1</div>
        <div class="flex-item">Item 2</div>
        <div class="flex-item">Item 3</div>
    </div>
</body>
</html>

Explanation: The display: flex; property creates a flex container, arranging its child elements (flex items) in a row by default. The flex: 1; property ensures that all items take up equal space within the container.

Key Takeaways

  • Flexbox Model: Flexbox organizes elements using a parent-child relationship (flex container and flex items).
  • Alignment: Simplifies vertical and horizontal alignment of items.
  • Flexibility: Adapts to dynamic and responsive layouts effortlessly.