Open In App

How to Display Three Columns Per Row in CSS Flexbox?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

CSS Flexbox is a one-dimensional layout model that allows items within a container to be arranged in rows or columns with dynamic sizing and alignment. It simplifies the process of creating complex layouts and responsive designs. In this article we will explore approach to arrange columns in a container so that there are three columns per row.

Approach

  • Create a parent <div> that will act as the flex container.
  • Place individual <div> elements inside the container, each representing a column.
  • Set display: flex it will turns the container into a flex container and use flex-wrap: wrap to allow items to wrap to new lines when necessary.
  • Use flex properties flex: 1 1 calc(33.333% - 10px) this ensures each item takes up approximately one-third of the container's width, considering the gap.
  • Add some other stylings as needed.

Example: In this example we are using CSS Flexbox layout to display the three columns per row.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Three Columns Layout</title>
    <link rel="stylesheet" href="style.css">

</head>

<body>
    <h1>Three Columns Layout</h1>
    <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 class="flex-item">Column 4</div>
        <div class="flex-item">Column 5</div>
        <div class="flex-item">Column 6</div>
    </div>
</body>

</html>
CSS
/* styles.css */
body {
    margin: 0;
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
}

.flex-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.flex-item {
    flex: 1 1 calc(33.333% - 20px);
    box-sizing: border-box;
    padding: 20px;
    background-color: #ffffff;
    border: 1px solid #ddd;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

h1 {
    text-align: center;
    color: #333;
    margin-bottom: 20px;
}

Output:

a2
Output

Next Article

Similar Reads