CSS Flexbox Layout

Flexbox lays out items along a single axis and distributes space between them, which makes responsive rows and columns simple.

What flexbox solves

Before flexbox, centring a box vertically or distributing space evenly required floats and hacks. Flexbox makes both trivial.

The container

.row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}

Key container properties

PropertyPurpose
flex-directionSets the main axis: row or column
justify-contentAligns items along the main axis
align-itemsAligns items along the cross axis
flex-wrapAllows items to move onto a new line
gapSpace between items

Key item properties

.sidebar { flex: 0 0 260px; }
.content { flex: 1 1 auto; min-width: 0; }

flex is shorthand for flex-grow, flex-shrink and flex-basis.

A responsive pattern

.cards {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}
.card {
    flex: 1 1 280px;
}

Each card wants 280px, grows to fill the row and wraps when there is not enough space, with no media query required.

Conclusion

Reach for flexbox when laying out one dimension, and CSS grid when you need rows and columns at the same time.

Useful resources

Hand picked references for this topic
Topics #Beginner #Web
Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All CSS notes →
Java

Introduction to Java

Java is a statically typed, object oriented language that compiles to bytecode and runs on a virtual machine, which is what makes it portable.

Read more

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.