Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

Flex Layout 2

Flexbox arranges items within a container in one direction, either in a Row (horizontal line) or Column (vertical line).

A Flexbox layout can be likened to a bookshelf with multiple books aligned in a row.

In this analogy, the bookshelf is the Flex Container, and the books within the shelf are the Flex Items.

HTML
<div class="flex-container">
<div class="flex-item">Book 1</div>
<div class="flex-item">Book 2</div>
<div class="flex-item">Book 3</div>
</div>

Aligning and Spacing in Flexbox

In Flexbox, justify-content aligns items along the main axis, while align-items aligns them along the cross axis.

These axes depend on the flex-direction property.

  • Main axis: When flex-direction is row, the main axis is horizontal. When flex-direction is column, it's vertical.

  • Cross axis: When flex-direction is row, the cross axis is vertical. When flex-direction is column, it's horizontal.


The gap property adjusts the spacing between flex items within a flexbox container.


justify-content

This property determines how items are aligned along the main axis of a flex container.

If the flex-direction is row, the main axis is horizontal. If it's column, the main axis is vertical.

Possible values

  • flex-start: Aligns items at the start of the main axis. Left if horizontal, top if vertical.

  • flex-end: Aligns items at the end of the main axis. Right if horizontal, bottom if vertical.

  • center: Centers items along the main axis. Horizontally center if the axis is horizontal, vertically center if the axis is vertical.

  • space-between: Creates equal space between items. No space at the start or end.

  • space-around: Adds equal space around each item, with half the space at the start and end compared to between items.

  • space-evenly: Distributes equal space between items and at the start/end.


align-items

This property sets how items are aligned along the cross axis of a flex container.

If flex-direction is row, the cross axis is vertical. If it's column, the cross axis is horizontal.


Possible values

  • flex-start: Aligns items at the start of the cross axis. Top if the main axis is horizontal, left if vertical.

  • flex-end: Aligns items at the end of the cross axis. Bottom if the main axis is horizontal, right if vertical.

  • center: Centers items along the cross axis. Vertically center if the main axis is horizontal, horizontally center if vertical.

  • stretch: Stretches items to fill the container's entire height or width along the cross axis.

  • baseline: Aligns flex items based on their baseline. The baseline typically refers to the bottom of the text within the items.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.