Explain Codes LogoExplain Codes Logo

Arrange 2 items per row using flexbox

html
responsive-design
css
flexbox
Nikita BarsukovbyNikita Barsukov·Jan 18, 2025
TLDR

Achieve a two-column flexbox layout by setting the container to display: flex; flex-wrap: wrap;, and assigning flex-basis: 50%; to each item. Thus, each item occupies half the container's width.

.container { /* Mothership ready for little item aliens */ display: flex; flex-wrap: wrap; } .item { /* Room for two? Make it so! */ flex-basis: 50%; /* Trust me, you need this */ box-sizing: border-box; }
<div class="container"> <div class="item">Item 1 (now with a friend!)</div> <div class="item">Item 2 (party of two!)</div> </div>

Voila! A flexible, two-column layout courtesy of flexbox.

Grasping flex-basis

The flex-basis property signifies an item's initial size before allocating any leftover space as per the flex factors. In the aforementioned example, flex-basis: 50%; means that every item should commandeer half the container's width.

Leveraging box-sizing

To count padding and borders effectively within the item's specified width, box-sizing: border-box; is used. This eliminates the possibility of unintended overflows.

Ensuring responsiveness

This approach boasts inherent responsive design attributes. Adjust the container's size, and the items will play along gracefully. The percentage widths keep the layout fluid across diverse screen sizes.

Responsive adaptations

Flexbox is tailor-made for responsive design. Use media queries to customise the layout for various screen sizes or orientations. You might even want a single-column layout on mobile:

@media (max-width: 600px) { .item { /* Going solo for the small screens */ flex-basis: 100%; } }

Creating gutters

To introduce space between items, margin comes to the rescue. Owing to its exclusion from box-sizing: border-box;, margins create gutters without interfering with width computations.

Conquering common pitfalls

Flex wrap on cramped containers

Items may prematurely wrap into a new row if the container width is too tight or if your padding/borders are generously large. Adjust flex-basis or deploy media queries to handle these scenarios.

Handling fraction widths

Subpixel rendering often varies across browsers. To maintain consistent layouts, round off widths or create fallbacks to nullify such issues.

Misusing tables

Stick to flexbox for layouts as it's a CSS-based solution. That way, your code remains semantic, manageable, and avoids table-oriented design blunders.