CSS Grid vs Flexbox: Which to Choose and When
Tahera Alam
Posted On: May 7, 2024
125981 Views
36 Min Read
Layout is one of the most important aspects of web design. It determines how the elements of a web page are arranged and displayed. This is where CSS Grid and Flexbox come into play – two powerful CSS layout features that help design how content appears on a webpage.
CSS Grid is a two-dimensional layout system that can help you lay out things neatly in horizontal and vertical dimensions. It is ideal for creating layouts where you want precise control over the position of elements. For example, you can use CSS Grid to create a magazine-style layout with equal-width columns or a flexible layout for images where the content can be displayed in different sizes. As shown in the image below.
On the other hand, Flexbox is one-dimensional and excels in arranging things in horizontal or vertical dimensions. It makes it great for creating navigation menus, lists, or groups of cards.
In this blog, we will learn everything you need to know before deciding between using a CSS Grid or a Flexbox. By the end of this blog, you’ll have a solid understanding of when and how to use a CSS Grid or a Flexbox.
So, let’s get started!
TABLE OF CONTENTS
Understanding CSS Grid
CSS Grid Layout (also known as CSS Grid) is a system that allows for two-dimensional layouts to be created on the web. CSS Grid makes creating responsive and flexible designs easier without relying heavily on complex positioning or float-based layouts.
CSS Grid works by dividing a container element into a grid of rows and columns. The child elements of the container are then placed into the grid, either automatically or by explicitly specifying their position. There are two main ways to place elements in a grid container:
- Automatic placement: This is the default mode, and it means that the browser will automatically place the elements in the grid according to their size and the size of the grid.
- Explicit placement: This mode allows you to specify the exact position of each element in the grid.
This flexibility in content placement makes the grid an ideal choice for creating complex layouts where you need to lay out elements in horizontal and vertical dimensions with precise control over the position of elements.
Below is a visualization of how a two-dimensional layout might look like:
In the below section of this blog on CSS Grid vs Flexbox, we will learn the key properties of CSS in detail.
Key Properties of CSS Grid
Before delving into the specific properties of CSS Grid, let’s take a moment to understand what makes it so useful.
In the past, creating complex multi-dimensional web layouts was challenging, involving complex hacks and workarounds to achieve the desired structure. However, CSS Grid has changed that by providing a straightforward way to arrange content into grids, making it easier to control the placement and alignment of elements.
It does this using key properties, including defining a grid container with display: grid, specifying the number of rows and columns using grid-template-rows and grid-template-columns, and aligning items within the grid using properties like justify-items and align-items.
These properties provide fine-grained control over web layouts, making creating responsive and complex designs easier.
Let’s now explore these properties in more detail:
display:grid
This is the property that we use to create a grid container. A grid container is just an HTML element we use to create a grid layout. It establishes a grid formatting context and allows us to organize child elements into a grid structure.
To create a grid container, simply use the display property with the value grid or inline-grid. Here’s an example:
HTML:
1 2 3 4 5 6 7 |
<div class="grid-container"> <div class="item">Selenium testing</div> <div class="item">Cypress testing</div> <div class="item">Browser testing</div> <div class="item">Playwright testing</div> <div class="item">Automation testing cloud</div> </div> |
CSS:
1 2 3 |
.grid-container { display: grid; } |
Now that we know how to create a grid layout let’s move on to see how to define rows and columns in a grid layout.
grid-template-columns
The grid-template-columns property specifies the number and width of columns in a grid layout. The values are a space-separated list, where each value specifies the width of the respective column.
For example, the following line would create a grid layout with two columns, each of which is 100px wide:
You can also use the repeat() function to create a repeating pattern of columns. For example, the following code would create a grid layout with three columns, each of which is 100px wide:
1 2 3 |
.grid-container { grid-template-columns: repeat(3, 100px); } |
grid-template-rows
Like grid-template-columns, the grid-template-rows property specifies the number and heights of rows in a grid layout. Each value specifies the height of the respective row.
For instance, the following line would create a grid with two rows of 100-px height:
Now that we understand how to define rows and columns in a grid layout, let’s learn how to use both grid-template-columns and grid-template-rows properties together with a practical example:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
<div class="grid-container"> <section class="left-section"> <p class="rating">4.8 out of 5 - G2 Crowd</p> <h1>They talk about it better than us</h1> <button> <a href="https://www.lambdatest.com/reviews" class="btn" >Read All Reviews</a> </button> </section> <div class="cards"> <div class="cards"> <!-- Card 1 --> <div class="card"> <a href="https://www.linkedin.com/posts/faisalkhatri_opensource-testing-lambdatest-activity-6936559414719983616-Fe0b/" target="_blank" > <div class="content"> <p> Thank you <span>@lambdatesting</span> for providing free open source license to run the web and mobile tests of our open source projects for free on LambdaTest platform. </p> </div> <div class="info"> <img src="https://www.lambdatest.com/resources/images/FaisalKhatri.png" alt="Jette Thrane" /> <div class="names"> <h2>Mohammad Faisal Khatri</h2> <p>@faisalkhatri</p> </div> </div> </a> </div> <!-- Card 2 --> <div class="card"> <a href="https://twitter.com/matgargano/status/1332857624329654273?s=20" target="_blank" > <div class="content"> <p> <span>@lambdatesting</span> is fantastic. Cross-browser and device testing frustration is minimized. You can't get rid of clients that need IE11, nor can you own every device, but LambdaTest bridges that gap. </p> </div> <div class="info"> <img src="https://www.lambdatest.com/resources/images/mat.png" alt="Mat Gargano" /> <div class="names"> <h2>Mat Gargano</h2> <p>@matgargano</p> </div> </div> </a> </div> <!-- Card 3 --> <div class="card"> <a href="https://twitter.com/recantha/status/1262383419645976576?s=20" target="_blank" > <div class="content"> <p> Really superb customer service from Arpit <span>@lambdatesting</span> Tricky Automation problem using Selenium in Python, and they talked me through it and got me up-and-running. Awesome. :-) </p> </div> <div class="info"> <img src="https://www.lambdatest.com/resources/images/Michael.png" alt="Michael (Mike) Horne" /> <div class="names"> <h2>Michael (Mike) Horne</h2> <p>@recantha</p> </div> </div> </a> </div> <!-- Card 4 --> <div class="card"> <a href="https://twitter.com/yesiamben/status/1222937857565822976?s=20" target="_blank" > <div class="content"> <p> Super top-notch customer support from <span>@lambdatesting</span> - just throwing it out there if you're looking for a decent browser testing platform, they get my full double thumbs up. Thumbs upThumbs up :-) </p> </div> <div class="info"> <img src="https://www.lambdatest.com/resources/images/ben.png" alt="Ben Pritchard" /> <div class="names"> <h2>Ben Pritchard</h2> <p>@yesiamben</p> </div> </div> </a> </div> <!-- Card 5 --> <div class="card"> <a href="https://twitter.com/mbrysonuk/status/1238148964693803009?s=20" target="_blank" > <div class="content"> <p> Second day using <span>@lambdatesting</span> and it's already proven itself a lot faster than Cross Browser Testing and BrowserStack, at half the price! Bargain </p> </div> <div class="info"> <img src="https://www.lambdatest.com/resources/images/matthew.png" alt="Matthew Bryson" /> <div class="names"> <h2>Matthew Bryson</h2> <p>@mbrysonuk</p> </div> </div> </a> </div> <!-- Card 6 --> <div class="card"> <a href="https://twitter.com/timwintle1979/status/1283430116723392512?s=20" target="_blank" > <div class="content"> <p> <span>@lambdatesting</span> can I just say, your support team is first class. I had the pleasure of talking with Prateek Singh. He went the extra mile and nothing was too much trouble. Clearly your support is also very technically adept, something which I really value. Thank you! </p> </div> <div class="info"> <img src="https://www.lambdatest.com/resources/images/TimothyWintle.png" alt="Timothy Wintle" /> <div class="names"> <h2>Timothy Wintle</h2> <p>@timwintle1979</p> </div> </div> </a> </div> </div> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #eef5ff; } .grid-container { display: grid; grid-template-columns: 2fr 2fr; /* Two columns: left and right */ gap: 10px; /* Gap between columns */ max-width: 1200px; margin: 0 auto; padding: 20px 40px; } .left-section { padding: 40px; display: flex; justify-content: center; flex-direction: column; } .left-section h1 { font-size: 3rem; color: #333; margin: 20px 0; } .left-section p { font-size: 18px; margin: 0; color: #0569ff; } button { padding: 18px 10px; background: #000; color: #ffffff; border: none; border-radius: 5px; font-size: 18px; width: 300px; margin-top: 10px; } a { text-decoration: none; color: inherit; } .cards { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 300px 350px 380px; gap: 10px; } .card { width: 300px; margin: 20px; background-color: #fff; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); border-radius: 8px; overflow: hidden; display: flex; flex-direction: column; color: #4a4a4a; } .card:hover { background-color: #0569ff; cursor: pointer; color: white; } .content { padding: 20px; } .content p { font-size: 16px; line-height: 1.5; margin: 0; } .info { display: flex; align-items: center; padding: 10px 20px; } .info img { width: 60px; height: 60px; border-radius: 50%; margin-right: 10px; } .names { flex-grow: 1; color: #000000; } .card:hover .names { color: white; } .names h2 { font-size: 18px; margin: 0; } .names p { color: #888; font-size: 14px; margin-top: 8px; } .card:hover .names p { color: white; } span { color: #0569ff; } .card:hover span { color: white; } |
See the Pen
grid-template-rows & grid-template-columns demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
The above example has a .grid-container element with two equal-sized columns. We use grid-template-columns to define the grid with two columns, each taking up an equal fraction of available space, creating a two-column layout.
1 2 3 4 5 |
.grid-container { display: grid; grid-template-columns: 2fr 2fr; /* Two columns: left and right */ gap: 10px; /* Gap between columns */ } |
To lay out the second column with the .cards class, we use another grid where we specify two columns and three rows using the below lines:
1 2 3 4 5 |
.cards { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 300px 350px 380px; } |
The grid-template-columns property sets the width of each column using the 1fr unit, which divides the available space equally between both columns. Similarly, the grid-template-rows property sets the height of the rows, with the first row being 300 pixels, the second row being 350 pixels, and the third row being 380 pixels.
justify-items
Like Flexbox, CSS Grid also provides an array of properties for controlling the alignment and positioning of grid items. One of these key properties is justify-items.
But, before discussing justify-items, let’s take a moment to learn all the essential properties related to alignment below.
Property | Description |
---|---|
justify-items | Align grid items along the inline axis (horizontally) within their cell. |
align-items | Aligns grid items along the block axis (vertically) within their cell. |
place-items | Shorthand for align-items and justify-items in one declaration. |
justify-content | Align the grid along the inline axis (horizontally) within the grid container, including extra space, if any. |
align-content | Align the grid along the block axis (vertically) within the grid container. |
place-content | Shorthand for align-content and justify-content in one declaration. |
justify-self | Aligns a single grid item along the inline axis within its cell. |
align-self | Aligns a single grid item along the block axis within its cell. |
place-self | Shorthand for align-self and justify-self in one declaration. |
The justify-items property aligns grid items along the row (inline) axis. It applies to all grid items within the grid container.
Below are the values you can use with the justify-items property:
- start: Align items to the start of the grid cell.
- end: Align items to the end of the grid cell.
- center: Align items to the center of the grid cell.
- stretch: This is the default value and expands items to fill the entire height of the grid cell.
Let’s look at an example to demonstrate this:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<h1>Justify Items Demo</h1> <div class="container"> <div class="item"> <a href="https://www.lambdatest.com/selenium-automation" target="_blank" >Test Selenium</a > </div> <div class="item"> <a href="https://www.lambdatest.com/cypress-testing" target="_blank" >Test Cypress</a > </div> <div class="item"> <a href="https://www.lambdatest.com/real-device-cloud" target="_blank" >Test apps on real device</a > </div> <div class="item"> <a href="https://www.lambdatest.com/playwright-testing" target="_blank" >Test Playwright</a > </div> </div> <div class="btn-wrapper"> <div> <label for="justifyItems">justify-items:</label> <select id="justifyItems"> <option value="stretch">stretch</option> <option value="start">start</option> <option value="end">end</option> <option value="center">center</option> </select> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
body { font-family: Arial, sans-serif; min-height: 100vh; background-color: hsl(210deg, 30%, 12%); } h1 { text-align: center; color: #fff; margin-bottom: 40px; } .container { border: 1px solid hsl(210deg, 10%, 40%); border-radius: 5px; padding: 10px; display: grid; grid-template-columns: 1fr 1fr; width: 500px; height: 300px; margin: 0 auto; gap: 8px; } .item { padding: 20px; border: none; color: #fff; font-size: 18px; background-color: #1b263b; border-radius: 5px; } a { color: inherit; text-decoration: none; } a:hover { text-decoration: underline; color: #0ebac5; } .btn-wrapper { display: flex; justify-content: center; margin: 20px 0; color: #fff; } select { padding: 10px; border-radius: 5px; border: none; background-color: #3b3b3b; color: #fff; font-size: 1rem; outline: none; } |
JavaScript:
1 2 3 4 5 |
const justifyItemsSelect = document.getElementById("justifyItems"); const container = document.querySelector(".container"); justifyItemsSelect.addEventListener("change", () => { container.style.justifyItems = justifyItemsSelect.value; }); |
See the Pen
justify-items demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
As we have understood the key properties above, in the below section of this blog on CSS Grid vs Flexbox, we will learn some of the benefits of CSS Grid in detail.
Benefits of CSS Grid
CSS Grid offers several benefits, making it an excellent choice for creating complex and grid-based layouts. Let’s take a look at some of them:
Two-dimensional layout
Unlike traditional layout methods focusing on rows or columns, CSS Grid allows you to simultaneously create complex layouts in both dimensions. This makes it ideal for arranging items in a grid format, such as magazine-style designs or responsive grid systems.
Overlap and layering
CSS Grid is great for overlapping elements and layering them on top of each other. To overlap elements in CSS Grid, you can use the grid-area property. The grid-area property specifies the grid area that an element should occupy. You can specify the area of the grid using a combination of row and column numbers.
For example, the following CSS code would overlap two elements:
1 2 3 4 5 6 7 8 |
.element1 { grid-area: 1 / 2; } .element2 { grid-area: 2 / 2; } |
Blend modes in CSS are a bit tricky, especially when you want solid text over a “blended” background. Surprisingly, a single-area grid layout is a pretty great way to have overlapping elements with codependent sizes but independent stacking contexts. pic.twitter.com/7FzevvT0ml
— Andy Jakubowski (@jakubowskiandy) July 23, 2021
This method is useful for creating intricate designs and visual effects that would be challenging to achieve with other layout methods.
Flexible sizing
CSS Grid allows you to use flexible units like fr (fractional unit) to define column and row sizes. The fr unit represents a fraction of the available space. For example, the following code would create a grid with three columns that are all the same width:
1 |
grid-template-columns: 1fr 1fr 1fr; |
This is particularly useful for distributing available space proportionally among grid items. To learn more about fr (fractional unit) in CSS, follow this guide on CSS units and get detailed insights.
Let’s look at the below visualization to understand it better:
Reduced HTML nesting
CSS Grid reduces the need for complex nested HTML structures common with other layout methods. This can lead to cleaner and more maintainable code.
In the traditional approach to creating layouts, you often used HTML elements like <div> or <section> to structure your page into rows and columns. For example, if you want to create a grid-like layout, you might have to create several nested <div> elements to define the rows and columns of your grid. This can lead to much extra HTML code, making your structure more complex and harder to manage.
With CSS Grid, instead of adding extra HTML elements to define your grid structure, you can define rows and columns directly in your stylesheet using properties like grid-template-columns and grid-template-rows. This means you can create rows and columns without nested HTML elements, making your code cleaner and maintainable.
In the below section of this blog on CSS Grid vs Flexbox, we will learn real-world examples where CSS Grid is implemented and currently being adapted and used.
Real-World Examples of CSS Grid
CSS Grid plays a crucial role in contemporary web design because of Its ability to create intricate and responsive layouts. Below, we explore some real-world websites that leverage CSS Grid to achieve sophisticated and responsive designs:
Airbnb: Airbnb, a popular online marketplace for vacation rentals and lodging, utilizes CSS Grid in its layout to organize property listings, search results, and filters, allowing users to navigate and explore available accommodations easily.
It is essential to make your website responsive on all devices and screen sizes. One significant aspect of achieving this responsiveness is adopting a mobile-first design approach, where you prioritize designing for mobile devices and progressively enhance the experience for larger screens.
Leading businesses widely embrace this approach. For instance, below is the Airbnb website rendered on different screen sizes:
You can ensure your website is responsive across different screen sizes by using a cloud-based platform like LambdaTest. It’s a platform that allows you to run manual and automated tests on over 3000 real devices, browsers, and operating system combinations. One of its features, LT Browser, helps you check your website’s responsiveness. We will delve into this feature in more detail later.
Test the responsiveness of your website across 53+ device viewports. Try LT Browser now!
National Geographic: National Geographic’s website uses CSS Grid to organize and display its visually rich content, including articles, images, and videos, in a structured and visually appealing manner.
The New York Times: The New York Times, a prominent news organization, uses CSS Grid for its homepage layout and various article pages to present diverse content in a clean and organized grid format.
Now that we have a clear understanding of CSS Grid and its benefits with real-world examples, in the below section of this blog on CSS Grid vs Flexbox, we will learn everything about CSS Flexbox in detail.
Understanding CSS Flexbox
CSS Flexbox, also known as the CSS Flexible Box Layout, was introduced in 2009. It emerged to address the complexities and limitations of traditional layout models, offering developers a more efficient and intuitive way to design responsive and dynamic web layouts.
Flexbox is a one-dimensional layout system that allows you to distribute and arrange a group of items in rows or columns. By one-dimensional, we mean it deals with rows or columns at a time but not both. It makes it particularly well-suited for distributing content along a single axis(either horizontal or vertical).
In the below section of this blog on CSS Grid vs Flexbox, we will learn the key properties of Flexbox in detail.
Key Properties of Flexbox
Understanding when to use Flexbox and how it works is essential. In this section, we will explore its essential properties and discuss how Flexbox works.
CSS consists of many different layout algorithms, known as “layout modes.” Every layout mode in CSS is like its own tiny sub-language with different characteristics. The default layout mode is Flow layout, but we can opt into Flexbox by changing the display property on the parent container.
display:flex
display:flex is the property we use to make a container a flex container.
When you apply display: flex; to a container, it becomes a flex container, and its immediate children become flex items. The container’s direct children are treated as flex items and are laid out according to the rules of Flexbox.
Below is an example:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="container"> <div class="layout-options"> <span>display:</span> <label> <input type="radio" name="layout" value="block" checked /> block </label> <label> <input type="radio" name="layout" value="flex" />flex </label> </div> <div class="grid-container"> <div class="item">Selenium testing</div> <div class="item">Cypress testing</div> <div class="item">Playwright testing</div> <div class="item">HyperExecute</div> <div class="item">Real-devices cloud</div> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
body { font-family: Arial, sans-serif; color: white; min-height: 100vh; background-color: hsl(210deg, 30%, 12%); } .container { padding: 10px; } .layout-options { text-align: center; margin-bottom: 25px; } .grid-container { border: 1px solid hsl(210deg, 10%, 40%); border-radius: 5px; padding: 10px; margin: 0 auto; max-width: 1200px; } .flex { display: flex; } .flex .item { margin-right: 10px; } .block { display: block; } .item { color: #fff; font-size: 20px; font-weight: bold; background-color: hsl(210deg, 40%, 20%); border-radius: 5px; padding: 10px 20px; margin-bottom: 10px; } |
JavaScript:
1 2 3 4 5 6 7 8 9 |
const layoutOptions = document.querySelector(".layout-options"); const gridContainer = document.querySelector(".grid-container"); layoutOptions.addEventListener("change", (event) => { const selectedLayout = event.target.value; gridContainer.classList.remove("block", "flex"); gridContainer.classList.add(selectedLayout); }); |
See the Pen
display flex demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
In this example, we have a container(with the class .grid-container) and a few child elements inside it.
By default, the container has a block layout that stacks the child elements vertically, creating a column-like structure. But when we change the container’s display to flex, it creates a flex formatting context and arranges all the child elements in a row, side by side according to the default flexbox layout algorithm.
Let’s now see how we can change this default behavior of Flexbox using the next property.
flex-direction
By default, items of a flex container will stack side by side in a row, but you can change that using the flex-direction property.
The most commonly used flex directions are row and column. Setting the flex-direction to a row will arrange elements from left to right, and setting it to a column will arrange elements in a column from top to bottom.
1 2 3 |
.container { flex-direction: row | column; } |
You can also use row-reverse and column-reverse to reverse the elements’ directions, but these have limited practical applications and are rarely used.
1 2 3 |
.container { flex-direction: row-reverse| column-reverse; } |
When you set the flex direction to row-reverse, the elements are laid out from right to left. The first item is at the right end, and the subsequent items follow towards the left.
Similarly, with flex-direction set to column-reverse, the items will be positioned in a column from bottom to top instead of top to bottom.
An important thing to understand here is the concept of axis, which plays a pivotal role in how flex layouts work. When you set the flex-direction property, you define the flex container’s main axis and cross-axis.
The main axis is along which the flex items are laid out inside a flex container. The cross axis is the axis perpendicular to the main axis.
If you set flex-direction to row, the main axis will run horizontally, and the cross axis will run vertically. In this case, elements will align along the main axis in a row, from left to right.
On the other hand, if you use flex-direction: column, the main axis will run vertically from top to bottom, and the cross axis will run horizontally from left to right. The elements will stack up along the main axis in a column, from top to bottom.
Here’s a quick visualization of both the scenarios:
justify-content
The justify-content property controls the alignment and distribution of flex items along the flex container’s main axis.
It provides several options that allow us to position and distribute items within the container. We can group all the items in a specific place using flex-start, center, and flex-end properties, or we can space them out using space-between, space-around, and space-evenly.
Here are the possible values for the justify-content property:
- flex-start: This is the default value. It aligns flex items at the beginning of the container’s main axis.
- flex-end: This aligns flex items at the end of the container’s main axis.
- center: It centers flex items along the main axis of the container.
- space-between: This value distributes flex items evenly along the main axis, leaving no space before the first item and after the last item.
- space-around: This distributes flex items evenly along the main axis with equal space before the first item and after the previous item. The space between the remaining items is also equal.
- space-evenly: This distributes flex items evenly along the main axis with equal space between them, including before the first item and after the last item.
Let’s look at an example to understand this:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<h1>Justify Content Demo</h1> <div class="container"> <div class="item"> <a href="https://www.lambdatest.com/selenium-automation" target="_blank" >Selenium testing</a > </div> <div class="item"> <a href="https://www.lambdatest.com/cypress-testing" target="_blank" >Cypress testing </a> </div> <div class="item"> <a href="https://www.lambdatest.com/real-device-cloud" target="_blank" >Real devices cloud</a > </div> <div class="item"> <a href="https://www.lambdatest.com/playwright-testing" target="_blank"> Playwright testing</a > </div> </div> <div class="btn-wrapper"> <div> <label for="flexDirection">flex-direction:</label> <select id="flexDirection"> <option value="row">row</option> <option value="column">column</option> </select> </div> <div> <label for="justifyContent">justify-content:</label> <select id="justifyContent"> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="center">center</option> <option value="space-between">space-between</option> <option value="space-around">space-around</option> <option value="space-evenly">space-evenly</option> </select> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
body { font-family: Arial, sans-serif; min-height: 100vh; background-color: hsl(210deg, 30%, 12%); } h1 { text-align: center; color: #fff; margin-bottom: 40px; } .container { border: 2px solid hsl(210deg, 10%, 40%); border-radius: 5px; padding: 20px 15px; display: flex; width: 800px; margin: 0 auto; gap: 8px; } .item { padding: 10px; border: 1px solid hsl(210deg, 10%, 40%); display: flex; border-radius: 5px; text-transform:capitalize; } a { color: white; text-decoration: none; } a:hover { text-decoration: underline; color: lightblue; } label { color: #fff; font-weight: bold; } .btn-wrapper { display: flex; justify-content: center; gap: 20px; margin: 25px 0; } select { padding: 10px; border-radius: 5px; border: none; background-color: #3b3b3b; color: #fff; font-size: 1rem; outline: none; } .select-container { display: flex; gap: 10px; margin-top: 10px; } |
JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const flexDirectionSelect = document.getElementById("flexDirection"); const justifyContentSelect = document.getElementById("justifyContent"); const container = document.querySelector(".container"); flexDirectionSelect.addEventListener("change", () => { container.style.flexDirection = flexDirectionSelect.value; }); justifyContentSelect.addEventListener("change", () => { container.style.justifyContent = justifyContentSelect.value; }); |
See the Pen
justify content demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
align-items
The align-items property controls flex items’ alignment along the flex container’s cross-axis. The cross axis is perpendicular to the main axis, which, as we mentioned, is determined by the flex-direction property.
The align-items property allows us to align items vertically (if the main axis is horizontal) or horizontally (if the main axis is vertical).
Here are the values for the align-items property:
- stretch: This is the default value for the cross-axis alignment. It causes flex items to stretch along the cross-axis to fill the container’s height (if the main axis is horizontal) or width (if the main axis is vertical).
- flex-start: It aligns flex items at the start of the cross-axis.
- flex-end: This aligns flex items at the end of the cross-axis.
- center: It centers flex items along the cross-axis.
- baseline: This aligns flex items such that their baselines are aligned.
Let’s look at an example to visualize this:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<h1>justify-content & align-items demo</h1> <div class="container"> <div class="item"> <a href="https://www.lambdatest.com/selenium-automation" target="_blank" > Selenium testing</a > </div> <div class="item"> <a href="https://www.lambdatest.com/cypress-testing" target="_blank" >Cypress testing</a > </div> <div class="item"> <a href="https://www.lambdatest.com/real-device-cloud" target="_blank" >Real devices cloud</a > </div> <div class="item"> <a href="https://www.lambdatest.com/playwright-testing" target="_blank" >Playwright testing</a > </div> </div> <div class="btn-wrapper"> <div> <label for="flexDirection">flex-direction:</label> <select id="flexDirection"> <option value="row">row</option> <option value="column">column</option> </select> </div> <div> <label for="justifyContent">justify-content:</label> <select id="justifyContent"> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="center">center</option> <option value="space-between">space-between</option> <option value="space-around">space-around</option> <option value="space-evenly">space-evenly</option> </select> </div> <div> <label for="alignItems">align-items:</label> <select id="alignItems"> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="center">center</option> <option value="baseline">baseline</option> <option value="stretch">stretch</option> </select> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
body { font-family: Arial, sans-serif; min-height: 100vh; background-color: hsl(210deg, 30%, 12%); } h1 { text-align: center; color: white; margin-bottom: 40px; } .container { border: 1px solid hsl(210deg, 10%, 40%); border-radius: 5px; padding: 10px; display: flex; width: 800px; margin: 0 auto; gap: 10px; } .item { padding: 15px; border: none; display: flex; font-size: 18px; background-color: #1b263b; border-radius: 5px; text-transform: capitalize; } a { color: white; text-decoration: none; } label { color: #fff; font-weight: bold; } .btn-wrapper { display: flex; justify-content: center; gap: 20px; margin: 20px 0; } select { padding: 10px; border-radius: 5px; border: none; background-color: #3b3b3b; color: #fff; font-size: 1rem; outline: none; } |
JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const flexDirectionSelect = document.getElementById("flexDirection"); const justifyContentSelect = document.getElementById("justifyContent"); const alignItemsSelect = document.getElementById("alignItems"); const container = document.querySelector(".container"); flexDirectionSelect.addEventListener("change", () => { container.style.flexDirection = flexDirectionSelect.value; }); justifyContentSelect.addEventListener("change", () => { container.style.justifyContent = justifyContentSelect.value; }); alignItemsSelect.addEventListener("change", () => { container.style.alignItems = alignItemsSelect.value; }); |
See the Pen
align-items demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
As we understand the key properties above, in the below section of this blog on CSS Grid vs Flexbox, we will learn some of the benefits of Flexbox in detail.
Benefits of Flexbox
Flexbox offers many benefits that streamline how we structure and design layouts. Let’s take a look at some of these benefits to see how they can be used to create flexible web layouts:
Efficient for aligning and distributing content
Flexbox is extremely handy for aligning and distributing elements within containers. Its properties, such as justify-content and align-items, make horizontal and vertical alignment effortless.
Visual cheat sheets for CSS Grid Layout and Flexbox. With everything from alignment to auto-flow.
↬ Flexbox Cheatsheethttps://t.co/DWyQDMNff7
↬ Grid Cheatsheethttps://t.co/QyUXrdVDao pic.twitter.com/GtdAt7h9TT
— Smashing Magazine 🇺🇦 🏳️🌈 (@smashingmag) August 18, 2018
Flexbox Alignment Cheatsheet
📏🎨🖍️📐#CSS #100DaysOfCode #CodeNewbie pic.twitter.com/3wHT2zUcT6— Bernardo Torres (@BernardoT0rres) January 30, 2021
Simplifies responsive design
Flexbox makes creating responsive layouts that adapt to different screen sizes easily. One of the key features that facilitate this responsive design using flexbox is its ability to control the behavior of items within a container using properties like flex-wrap, flex-grow, flex-shrink, and flex-basis.
Let’s briefly break down each of these properties to understand how they help in making a layout responsive:
- flex-wrap: This property determines whether items should wrap to the next line when there’s insufficient space within the container. By utilizing this property, you can ensure that elements rearrange themselves neatly as the screen size changes.
- flex-grow: This property specifies how much an item should grow about its siblings when there’s extra space available within the container.
- flex-shrink: In cases where the container becomes too narrow to accommodate all items at their specified sizes, the flex-shrink property determines the degree to which each item should shrink. This avoids overflowing content and maintains the overall layout structure.
- flex-basis: This property sets the initial size of an item before any available space is distributed. By using it, you can establish a starting point for item sizes, preventing unexpected sizing behaviors.
- do I only need to control the layout by row or column – use a flexbox
- do I need to control the layout by row and column – use a grid
- Global support: Flexbox uses widespread support, with a global usage of 97.7%. Unprefixed support stands at 97.53%.
- Key supported properties: Most modern browsers support key Flexbox properties like display: flex, align-items, justify-content, and more.
- Partial support: Some older versions of browsers offer partial support for Flexbox properties, often related to outdated specifications or syntax.
- Exceptions: Opera 10-11.5 and Internet Explorer 6-9 do not support Flexbox. Internet Explorer 10 and 11 have partial support with certain limitations.
- Cross-device and cross-browser compatibility: It is well-supported across mobile browsers like Chrome for Android, Safari for iOS, and Firefox for Android.
- Global support: It has a global usage of 95.61%, making it a widely adopted layout technique.
- Supported properties: It supports all grid-* properties and the fractional unit (fr unit).
- Partial support: Similar to Flexbox, some browsers offer partial support for CSS Grid in older versions, often due to adherence to previous specifications.
- Exceptions: Chrome versions 4-28 and Firefox versions 2-39 do not support CSS Grid. However, most modern versions of these browsers provide full support.
- Cross-device and cross-browser compatibility: It is well-supported on mobile browsers, including Chrome for Android, Safari for iOS, and Firefox for Android.
- Complex header/footer structures: In many web designs, headers and footers contain elements like logos, navigation menus, social media links, and additional content.
- Card-based layouts: Card-based layouts are a common design pattern for displaying content like articles, products, prices, or user profiles. CSS Grid can help create a grid of cards with consistent spacing, while Flexbox can be applied within each card to manage content alignment, such as titles, images, and descriptions.
- Sidebar with main content: When designing a website with a sidebar and main content area, CSS Grid can define the overall page structure, allocating space for both the sidebar and the main content.
Use CSS flex wrap property for creating responsive flex containers 👨💻📚 pic.twitter.com/BcqWHMAcxg
— David Mraz (@davidm_ml) June 7, 2023
By assigning appropriate flex-grow values to different items, you can control which elements expand more than others, distributing space efficiently and maintaining a balanced layout.
#Flexbox30 Day 21 ✨
I mentioned in the beginning that Flexbox is great for responsive design. This is where it shines. "flex-grow" allows our flex item to grow if necessary. So if there is extra free space in my container, it will automatically fill that space! CRAZY 🤯 pic.twitter.com/HlJPMYwXBO
— Samantha Ming (@samantha_ming) September 21, 2019
CSS flex-shrink Property 👇 pic.twitter.com/ziT81h7vXQ
— Ali (@alicalimli_dev) January 26, 2023
✨ CSS Tip ✨
The flex-basis property in CSS allows you to set the preferred length of a flex-item and takes priority over the width property.
Check out the example below! 🙌 pic.twitter.com/L92F4Vofnh
— Braydon Coyer (@BraydonCoyer) June 3, 2022
Creating a responsive website requires careful consideration of key factors to avoid common issues. Follow this blog on best practices for responsive websites to ensure they are effective and user-friendly. By using these flexbox properties, you can create layouts that adapt to different screen sizes and devices without having to write extensive media queries.
Auto-adjustment of container items
Flexbox automatically adjusts the size of items within a flex container to fit the available space. This eliminates the need for setting fixed widths or heights for each element, making the layout more adaptable to varying content lengths.
Below is an example:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div class="card-container"> <div class="card"> <h2>Card 1</h2> <p>This is a short card content.</p> </div> <div class="card"> <h2>Card 2</h2> <p>This card has slightly longer content, but it still fits well.</p> </div> <div class="card"> <h2>Card 3</h2> <p>This card contains a longer piece of content that might span multiple lines, but Flexbox takes care of the height.</p> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
body { margin: 0; font-family: Arial, sans-serif; background-color: #f5f5f5; } .card-container { display: flex; gap: 20px; justify-content: space-between; padding: 20px; max-width: 1200px; margin: 0 auto; } .card { flex: 1; background-color: #fff; border: 1px solid #ddd; padding: 20px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } h2 { margin: 0; font-size: 1.5rem; } p { margin: 10px 0; } |
See the Pen
flexbox auto-adjustment demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
In the example, the .card-container uses a Flexbox to create a row of cards. The .card elements automatically adjust their heights based on the content inside them. Even though the content within the cards varies in length, Flexbox ensures that the cards have equal height and maintain a neat and organized layout.
In the below section of this blog on CSS Grid vs Flexbox, we will learn real-world examples where Flexbox is implemented and currently being adapted and used.
Real-World Examples of Flexbox
Flexbox is widely employed in modern web design for its versatility and efficiency. In fact, it’s rare to encounter a website that doesn’t rely on Flexbox to organize and present content neatly. Here are some real-world examples showcasing its effectiveness:
Amazon: Amazon, the largest eCommerce platform in the world, uses Flexbox in its layout to make it responsive and user-friendly:
Apple: Apple, the technology giant, makes extensive use of flexbox in its layout to make it sleek and eye-catching.
GitHub: GitHub, the code hosting and collaboration platform, utilizes Flexbox for many layout components, such as navigation menus, repository listings, user profiles, etc.
Medium: Medium, a popular platform for publishing articles, uses Flexbox for various layout elements on its homepage and article pages.
Now that we have a better understanding of CSS Grid and Flexbox in detail, in the below section of this blog on CSS Grid and Flexbox, we will leave when to choose which layout for better structuring and user experience.
CSS Grid vs Flexbox: Which to Choose and When?
CSS Grid and Flexbox both offer their own unique ways to create flexible and responsive layouts. Having said that, they have their own set of strengths and shortcomings.
In this section, let’s learn some of them so that you can make informed decisions when it comes to choosing the layout that best fits your needs.
One-dimensional versus two-dimensional layout
The most important thing you need to know about CSS Grid and Flexbox is that Flexbox is for one-dimensional layouts, and CSS Grid is for two-dimensional layouts.
The following tweet from Rachel Andrew summarizes this difference gracefully:
Flexbox is for one dimensional layout. A row OR a column. Grid is for two dimensional layout. Rows AND columns.
— Rachel Andrew (@rachelandrew) January 25, 2019
If you want a layout that only flows in one direction – either horizontal or vertical, Flexbox might be the best way to go. Flexbox is one-dimensional and is excellent for arranging elements along a single axis (either in rows or columns).
On the other hand, if you want a layout where elements need to be arranged horizontally and vertically involving both rows and columns, a CSS Grid might be the right choice.
CSS Grid is well suited for scenarios like this, where a design calls for items to be aligned in horizontal and vertical directions.
To better understand this, let’s look at an example of a one-dimensional layout using Flexbox followed by a multi-dimensional layout using a CSS Grid.
Demo: One-dimensional layout using Flexbox
In this section, we will learn how to create a one-dimensional layout using Flexbox. As learned above, Flexbox is the best choice for arranging items in a row or column, which is a simple and efficient way to design flexible and responsive layouts.
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<nav class="navbar"> <div class="navbar-logo"> <img src="https://www.lambdatest.com/resources/images/logos/logo.svg" alt="LambdaTest Logo" /> </div> <ul class="navbar-links"> <li> <a href="https://www.lambdatest.com/online-browser-testing" >Browser testing</a > </li> <li> <a href="https://www.lambdatest.com/cypress-testing" >Cypress testing</a > </li> <li><a href="https://www.lambdatest.com/blog/">Blogs</a></li> </ul> <div class="navbar-right-side"> <div><a href="https://accounts.lambdatest.com/login">Sign In</a></div> <button> <a href="https://accounts.lambdatest.com/register" >Get started free</a > </button> </div> </nav> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
/* Reset default margins and paddings */ * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; color: #111; } /* Navigation bar styles */ .navbar { background-color: #ffffff; display: flex; justify-content: space-between; align-items: center; padding: 15px 40px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); } .navbar-logo img { max-height: 40px; } .navbar-links { list-style: none; display: flex; } .navbar-links li { margin-right: 25px; } .navbar-links a { text-decoration: none; color: inherit; transition: color 0.3s ease; } .navbar-links a:hover { color: #7606bd; } .navbar-right-side { display: flex; align-items: center; } .navbar-right-side > div { margin-right: 25px; } .navbar-right-side a { text-decoration: none; color: inherit; transition: color 0.3s ease; } .navbar-right-side div:hover { color: #7606bd; } .navbar-right-side button { background: linear-gradient(91.88deg, #2c57f3 0.88%, #a506d8 98.71%); border: none; color: white; padding: 10px 20px; font-weight: bold; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; } .navbar-right-side button:hover { background-color: #6004a5; } |
See the Pen
one dimensional layout example by Tahera Alam (@alam_tahera)
on CodePen.
Result:
Code Walkthrough:
In this example, we have a simple navigation menu (<nav> element) with three direct child elements. We are using Flexbox to arrange these elements in a horizontal row.
We made the nav element with the .navbar class a flex container by setting display: flex to it.
This sets the container as a flex container, meaning the child items inside the container will be laid out according to the default flexbox layout algorithm. In a flex container, you can use properties like justify-content and align-items to control how the items are positioned along the main and cross axes, respectively.
We then set justify-content to space-between and align-items to center, which creates space between all three flex items and centers them vertically.
The last item of the flex container is a <div> element with a nested <div> and a button inside it. By default, it has a display block, which makes both elements stack as columns but we want to arrange them in a row.
So, we used display: flex again, which arranges them in a row since the default flex-direction is a row. An important thing to note here is that Flexbox is not only great for creating a one-dimensional layout but also handy for alignment within a flex container itself.
With this setup, we have created a horizontal navigation menu using Flexbox that is ideal for this layout because it deals with elements in one dimension, allowing us to arrange the menu items side by side easily.
Now that we know what a one-dimensional layout looks like and how Flexbox excels in creating one, let’s move on to creating a two-dimensional layout in the section below.
Demo: Two-dimensional layout using CSS Grid
In this section, we will learn how to create a two-dimensional layout using CSS Grid.
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
<h1 class="heading">Masonry Image Layout using CSS Grid</h1> <div class="grid-wrapper"> <div> <img src="https://images.unsplash.com/photo-1541845157-a6d2d100c931?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1588282322673-c31965a75c3e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1351&q=80" alt="" /> </div> <div class="tall"> <img src="https://images.unsplash.com/photo-1588117472013-59bb13edafec?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="" /> </div> <div class="wide"> <img src="https://images.unsplash.com/photo-1587588354456-ae376af71a25?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div> <img src=" https://images.unsplash.com/photo-1558980663-3685c1d673c4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=60" alt="" /> </div> <div class="tall"> <img src="https://images.unsplash.com/photo-1588499756884-d72584d84df5?ixlib=rb-1.2.1&auto=format&fit=crop&w=2134&q=80" alt="" /> </div> <div class="big"> <img src="https://images.unsplash.com/photo-1588492885706-b8917f06df77?ixlib=rb-1.2.1&auto=format&fit=crop&w=1951&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1588247866001-68fa8c438dd7?ixlib=rb-1.2.1&auto=format&fit=crop&w=564&q=80" alt="" /> </div> <div class="wide"> <img src="https://images.unsplash.com/photo-1586521995568-39abaa0c2311?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div class="big"> <img src="https://images.unsplash.com/photo-1572914857229-37bf6ee8101c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1951&q=80" alt="" /> </div> <div class="tall"> <img src="https://images.unsplash.com/photo-1588453862014-cd1a9ad06a12?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1588414734732-660b07304ddb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1588224575346-501f5880ef29?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1574798834926-b39501d8eda2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1547234935-80c7145ec969?ixlib=rb-1.2.1&auto=format&fit=crop&w=1353&q=80" alt="" /> </div> <div class="wide"> <img src="https://images.unsplash.com/photo-1588263823647-ce3546d42bfe?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1587732608058-5ccfedd3ea63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1587897773780-fe72528d5081?ixlib=rb-1.2.1&auto=format&fit=crop&w=1489&q=80" alt="" /> </div> <div class="wide"> <img src="https://images.unsplash.com/photo-1588083949404-c4f1ed1323b3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1489&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1587572236558-a3751c6d42c0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div class="wide"> <img src="https://images.unsplash.com/photo-1583542225715-473a32c9b0ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div class="big"> <img src="https://images.unsplash.com/photo-1527928159272-7d012024eb74?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1553984840-b8cbc34f5215?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1433446787703-42d5bf446876?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1351&q=80" alt="" /> </div> <div class="big"> <img src="https://images.unsplash.com/photo-1541187714594-731deadcd16a?ixlib=rb-1.2.1&auto=format&fit=crop&w=700&q=80" alt="" /> </div> <div class="tall"> <img src="https://images.unsplash.com/photo-1540979388789-6cee28a1cdc9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1421930866250-aa0594cea05c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1355&q=80" alt="" /> </div> <div> <img src="https://images.unsplash.com/photo-1493306454986-c8877a09cbeb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1381&q=80" alt="" /> </div> <div class="wide"> <img src="https://images.unsplash.com/photo-1536466528142-f752ae7bdd0c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" alt="" /> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
/* Reset CSS */ * { margin: 0; padding: 0; box-sizing: border-box; } html, body { padding: 25px; background: #000814; } h1 { font-family: "Helvetica Neue", sans-serif; font-size: 2rem; text-align: center; margin-bottom: 3rem; } img { max-width: 100%; height: auto; vertical-align: middle; display: inline-block; } .grid-wrapper > div > img { width: 100%; height: 100%; object-fit: cover; border-radius: 5px; } .grid-wrapper { display: grid; grid-gap: 15px; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); grid-auto-rows: 200px; grid-auto-flow: dense; } .grid-wrapper .wide { grid-column: span 2; } .grid-wrapper .tall { grid-row: span 2; } .grid-wrapper .big { grid-column: span 2; grid-row: span 2; } |
See the Pen
grid-layout demo by Tahera Alam (@alam_tahera)
on CodePen.
Result:
In this example, we created a two-dimensional image gallery using CSS Grid. Let’s break down the important parts.
The element with the .grid-wrapper class is the parent container of the images. So, first, we will set display: grid to it, which tells the browser to lay out the children of this element in a grid. Next, we use the grid-gap: 15px property to specify that there should be a gap of 15px between each grid item.
Moving on, we set the grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) property to define the columns of the grid.
The repeat() function tells the browser to create as many columns as necessary to fit all children but no more than the number specified in the argument. The minmax() function specifies that each column should be at least 250px wide but can be wider if necessary.
Next, we have the grid-auto-rows: 200px property specifies the height of each row in the grid. The grid-auto-flow: dense property tells the browser to pack the grid items as tightly as possible.
Notice how we use the .wide, .tall, and .big classes to style the images differently.
The .wide class makes the image take up two columns in the grid, while the .tall class makes the image take up two rows in the grid.
The .big class is used to make the image even larger. It makes the image take up two columns and two rows in the grid, resulting in the largest images of the layout.
With CSS Grid, we’ve created a multi-dimensional layout, organizing elements into rows and columns with ease. Achieving this with Flexbox would require complex CSS workarounds, as Flexbox is more suited for one-dimensional layouts. CSS Grid’s explicit grid system makes it ideal for intricate multi-dimensional layouts like this one.
As MDN says, “A simple question to ask yourself when deciding between grid or flexbox is:
In this blog section on CSS Grid vs Flexbox, we will learn the concept of content first and layout first approaches in web design and which approach a designer or the developers choose.
Content First vs Layout First
When designing a website, designers or developers often face a fundamental choice: should they prioritize content or layout? The decision that will be made by either the designer or the developers significantly impacts the user experience and overall effectiveness of the website.
Let us learn which approach a designer or a developer will choose.
Flexbox is content-based, meaning it takes the content of the elements into account when creating the layout. This allows Flexbox to adjust the design to accommodate varying amounts of content automatically. In contrast, Grid is layout-based, focusing more on defining the overall structure of the layout rather than the content within it.
Let’s look at a few illustrations to understand this better:
Look at the above images, this is what we mean by “flexbox is content-based”.
Unlike Flexbox, which is content-based, the grid layout system is focused on creating structured layouts with defined rows and columns. Grid requires you to specify the exact layout you want, providing precise control over the placement of elements.
Let’s see what the previous illustrations would look like in case of a CSS Grid Layout:
As we can see, the grid sticks to its rows and columns irrespective of the content inside them; however, Flexbox changes its layout based on the content.
When deciding between CSS Grid vs Flexbox, it’s helpful to have a general guideline. Use CSS Grid when you have a specific layout structure in mind and need precise control. On the other hand, choose Flexbox when you prefer a more flexible approach to layout and want elements to fit naturally. It’s not always a clear-cut choice, so consider your goals and needs.
Additionally, you can combine CSS Grid and Flexbox for complex layouts, which you will learn later in the section.
In the below section of this blog on CSS Grid vs Flexbox, we will learn the browser compatibility that each layout offers in detail.
Browser Compatibility
In the modern day of web design, CSS Grid vs Flexbox are the two most used layout methods. Ensuring compatibility of these tools across different browsers and devices is crucial to delivering a consistent user experience.
So, let’s look at the browser compatibility of Flexbox, followed by the CSS Grid.
Compatibility of Flexbox
CSS Flexbox layout module is widely supported across modern browsers, making it a reliable choice for creating flexible layouts. As of the latest data:
Here’s an illustration that shows its support in detail:
Compatibility of CSS Grid
CSS Grid Layout enables the creation of grid-based layouts. Let’s look at a summary of the compatibility of CSS Grid:
The below illustration provides a detailed view of the support for CSS Grid:
In the below section of this blog on CSS Grid vs Flexbox, we will learn when to use CSS Grid and Flexbox effectively for complex layouts.
Combining CSS Grid and Flexbox – When to Use Both?
CSS Grid and Flexbox can be used together to create complex layouts that take advantage of the strengths of both layout systems. In fact, combining both is a widely used practice, making layout creation even simpler and more efficient.
Here are some of the cases where you might want to use both:
CSS Grid is great for creating the overall structure of the header/footer, while Flexbox can be used inside grid items to arrange the individual elements.
For instance, you can use CSS Grid to create rows or columns for the header/footer and then use Flexbox within those grid items to center-align navigation menus or arrange social media icons horizontally.
This combination allows you to maintain a uniform grid structure while fine-tuning the alignment and distribution of content within individual cards.
Within the main content area, a Flexbox can be used to arrange various sections vertically or horizontally, depending on the design requirements. This mix ensures that the main content area’s internal layout is optimized using Flexbox while the broader page structure is established with CSS Grid.
Now that we know that combining CSS Grid and Flexbox might be a good choice, let’s build a layout using both Grid and Flexbox to solidify this knowledge.
Here’s a sneak peek of what we are going to build:
Result:
The above demo is displayed using LT Browsers, which helps you validate the website on various screen sizes. LambdaTest offers an LT Browser feature, which allows you to preview your website on a wide range of mobile devices. With more than 53 device viewports available, you can compare them side by side and synchronize interactions such as scrolling, clicking, and navigation. It provides pre-installed viewports for mobiles, tablets, desktops, and laptops.
To start using LT Browser and test the responsiveness of your application, simply click the download button below. Once the .exe file is downloaded, run it to access all the features and capabilities of LT Browser.
Watch the video tutorial below to become acquainted with the features and functionalities of LT Browser.
Subscribe to the LambdaTest YouTube Channel and get the latest updates on various automation testing tutorials covering Selenium testing, cross-device testing, Browser compatibility, and more.
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
<div class="grid-container"> <div class="item-1"> <a href="https://www.lambdatest.com/blog/best-ci-cd-tools/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2022/07/image27-3-1.png); " ></div> <article> <h1>38 Best CI/CD Tools For 2023</h1> <span>Himanshu Sheth</span> </article> </a> </div> <div class="item-2"> <a href="https://www.lambdatest.com/blog/selenium-manager-in-selenium-4-11-0/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2023/08/unnamed-60-1-1-1.png); " ></div> <article> <h1> Selenium Manager in Selenium 4.11.0: New Features and Improvements </h1> <p> Selenium WebDriver, as everyone knows, is used for automating browsers. It is used widely by many organizations for web automation testing... </p> <span>Faisal Khatri</span> </article> </a> </div> <div class="item-3"> <a href="https://www.lambdatest.com/blog/test-scenario-vs-test-case/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2023/07/test2520scenario2520vs2520test2520case2520og.png); " ></div> <article> <h1>Test Scenario vs Test Case: Core Differences</h1> <p> Test scenario and test case are the two commonly used terms in the software testing domain. These terms are regarded as the building block of testing... </p> <span>Nazneen Ahmad</span> </article> </a> </div> <div class="item-4"> <a href="https://www.lambdatest.com/blog/css-refactoring/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2023/03/unnamed252520-2525202023-03-15T174705.891.png); " ></div> <article> <h1>A Complete Guide to CSS Refactoring</h1> <p> Being a front-end developer is like having the magical power to shape reality after it’s been created... </p> <span>Adarsh Gupta</span> </article> </a> </div> <div class="item-5"> <a href="https://www.lambdatest.com/blog/css-cascade-layers/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2023/06/Complete-Guide-To-CSS-Cascade-Layers.png); " ></div> <article> <h1>A Complete Guide To CSS Cascade Layers</h1> <p> “Design is not just what it looks like and feels like. Design is how it works,” – Steve Jobs. These words perfectly capture the essence of creating captivating websites... </p> <span>Tahera Alam</span> </article> </a> </div> <div class="item-6"> <a href="https://www.lambdatest.com/blog/automating-react-virtual-dom-in-selenium/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2023/05/unnamed-2023-05-15T200510.802-1.png); " ></div> <article> <h1> Using React Virtual DOM To Improve Web Application Performance </h1> <p> If you don’t know, HTML is the most widely used markup language for creating web pages supported by all major browsers like Google Chrome, Mozilla Firefox, and Safari... </p> <span>Bonnie</span> </article> </a> </div> <div class="item-7"> <a href="https://www.lambdatest.com/blog/best-css-button-hover-effects/" class="card" target="_blank" > <div class="thumb" style=" background-image: url(https://www.lambdatest.com/blog/wp-content/uploads/2023/08/FI-1-1-1.png); " ></div> <article> <h1>41 Best CSS Button Hover Effects in 2023</h1> <p> Buttons are everywhere on the web; they have proven to be an indispensable component of modern web design... </p> <span>Alex Anie</span> </article> </a> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
html { background: #f5f7f8; font-family: "Roboto", sans-serif; -webkit-font-smoothing: antialiased; padding: 20px 0; } .grid-container { width: 90%; max-width: 1240px; margin: 0 auto; display: grid; grid-template-columns: 1fr; grid-template-rows: auto; grid-gap: 20px; } @media only screen and (min-width: 500px) { .grid-container { grid-template-columns: 1fr 1fr; } .item-1 { grid-column: 1 / span 2; } .item-1 h1 { font-size: 30px; } } @media only screen and (min-width: 850px) { .grid-container { grid-template-columns: 1fr 1fr 1fr 1fr; } } /* card */ .card { min-height: 100%; background: white; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); display: flex; flex-direction: column; text-decoration: none; color: #444; position: relative; top: 0; transition: all 0.1s ease-in; } .card:hover { top: -2px; box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2); } .card article { padding: 20px; display: flex; flex: 1; justify-content: space-between; flex-direction: column; } .card .thumb { padding-bottom: 60%; background-size: cover; background-position: center center; } .card p { flex: 1; line-height: 1.4; } h1 { font-size: 20px; margin: 0; color: #333; } .card span { font-size: 12px; font-weight: bold; color: #999; text-transform: uppercase; letter-spacing: 0.05em; margin: 2em 0 0 0; } |
See the Pen
Card-layout – combining CSS Grid and Flexbox by Tahera Alam (@alam_tahera)
on CodePen.
Result:
In this example, we created a responsive card-based layout using CSS Grid and Flexbox. Let’s break down the important parts of it.
Code Walkthrough:
The HTML structure consists of a grid container containing multiple grid items. Each grid item represents a card-like component containing a thumbnail image and an article with some content.
The .grid-container class defines the grid layout, which starts as a single-column layout and switches to a two-column layout on screens wider than 500px and a four-column layout on screens wider than 850px.
Below is the relevant code:
1 2 3 |
.grid-container { grid-template-columns: 1fr; } |
1 2 3 4 |
@media only screen and (min-width: 500px) { .grid-container { grid-template-columns: 1fr 1fr; } |
1 2 3 4 5 |
@media only screen and (min-width: 850px) { .grid-container { grid-template-columns: 1fr 1fr 1fr 1fr; } } |
The .card class represents the individual card component. The .card element is a flex container, and it has a flex-direction: column property that specifies that the flex items should be arranged in a column.
1 2 3 4 |
.card { display: flex; flex-direction: column; } |
The .card article class is also a Flexbox container for the card’s textual content, arranging the content in a column with even spacing between its elements.
1 2 3 4 5 6 7 |
.card article { display: flex; flex: 1; justify-content: space-between; flex-direction: column; padding: 20px; } |
Wrapping it up!
As web design trends evolve, layout systems like CSS Grid vs Flexbox will play a pivotal role in helping us meet the design requirements.
In this blog, we started by discussing the basics of both CSS Grid vs Flexbox and then moved to discuss when to use a CSS Grid and a Flexbox.
Choosing between CSS Grid vs Flexbox has no clear winner, and you need to make a pragmatic decision based on your design and project requirements. Remember, Flexbox is for layouts that need to deal with one dimension – either a row or a column and grid is for layouts that require multiple dimensions(both rows and columns).
Another point to consider is that Flexbox is the right fit when you are flexible about layout and just want elements to fit in, while the grid is ideal when you want to focus on the layout with precise control over the position of elements.
Frequently Asked Questions (FAQs)
Can I use CSS Grid or Flexbox with frameworks like Bootstrap or Foundation?
Yes, you can use CSS Grid or Flexbox alongside frameworks like Bootstrap or Foundation. These frameworks often provide grid systems that can be customized or overridden with CSS Grid or Flexbox.
Are there any performance considerations when using CSS Grid or Flexbox?
CSS Grid and Flexbox are highly efficient layout systems well-supported by modern browsers. However, using complex nested grids or excessive calculations in Flexbox can impact performance, so it’s best to keep layouts simple and optimized.
What is the disadvantage of CSS Flexbox?
Flexbox lacks support for creating complex two-dimensional layouts, as it is primarily a one-dimensional layout system.
Does Tailwind use Flexbox or grid?
Tailwind CSS primarily uses Flexbox for its layout system. However, it can also be used in conjunction with CSS Grid for more complex layouts.
Got Questions? Drop them on LambdaTest Community. Visit now