SAT.AUG.15
2026
22:22:04

CSS Flexbox

Learning about the basics of HTML & CSS

CSS flexbox is used to organize multiple HTML elements into rows OR columns.

In this section of the guide we will organise some items using flexbox.

Add this inside the body of your HTML document:

<div id="container">
	<p class="containerItem">1</p>
	<p class="containerItem">2</p>
	<p class="containerItem">3</p>
</div>

The paragraph elements are children of the div element, or contained within the div element.

By changing the display property of the container to flex, we can arrange the elements inside of it.

In CSS write:

#container {
  display: flex;
}

.containerItem {

}

Setting the display property to ‘flex’ makes the div our flex container, and it makes all of the elements inside of it flex items.

Any style changes we make in .containerItem will apply to all 3 p elements because they have the containerItem class.

Add this style to #container.

#container {
  display: flex; 
  flex-direction: row;        /* possible values: row, row-reverse, column, column-reverse */
  justify-content: center;  /* how items are placed horizontally */
  align-items: center;       /* how items are placed vertically */
}

Add borders, and add extra style to the container. Experiment with each of the new elements by changing their values in the code below to see how they behave.

#container {
  display: flex; 
  flex-direction: row;    
  justify-content: center; 
  align-items: center;       

  /* borders */
  border-style: solid;
  border-color: blue;

  /* to center the container */
  width: 50%;
  margin: auto;

  /*This spreads the items evenly across the container */
  justify-content: space-between; 

  /*add a gap between items*/
  gap: 20px;

}

.containerItem {
  border-style: solid;
  border-color: green;

  /*to center individual items */
  width: 50%;
  margin: auto;

}
Troubleshooting

If you don’t know why something doesn’t look how you expect, check your other classes to see if there are any conflicts. Sometimes different sections of your stylesheet will be modifying the same element, causing unpredictable behaviour.

Summary
  • Display: flex turns an element into a flexible container
  • Flex-direction sets the axis the container items should be laid out in
  • Justify-content and align-items control spacing and alignment
  • Flexbox is helpful for 1 dimensional layouts