justify-content
The justify-content
property is used for setting a layout pattern of flex items (nested child elements) along the main axis of the flex container. The main axis is typically the horizontal axis unless you set column
or column-reverse
in the flex-direction
property. We'll provide our explanation based on the default flex-direction
setting.
flex-start
This is the default setting. With this property value, flex items are laid out from the left edge.
Note: 'edge' means the endpoint with some distance from the edge of the element based on the container's paddings and flex item's margins.
center
With this property value, flex items are laid out in the center of the parent element.
flex-end
With this property value, flex items are pushed out to the right edge of the parent element.
space-between
With this property value, the first item is set on the left edge, and the last item is set on the right edge while other items are evenly distributed between the first item and the last item.
space-around
With this property value, items are evenly distributed. Unlike space-between, space-around creates a half-size space on both ends.
Practice
Objective:
Check how the justify-content property works
1. Update the body section in the HTML file
Add the code below in the <body>
section of the chapter15.html file. We are using the same classes as the ones set before. There is no need to set new classes.
<h2>justify-content</h2>
<h3>Original Position</h3>
<div class="flex-container" style="display: flex;">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
<h3>justify-content: flex-start</h3>
<div class="flex-container" style="display: flex; justify-content: flex-start;">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
<h3>justify-content: center</h3>
<div class="flex-container" style="display: flex; justify-content: center;">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
<h3>justify-content: flex-end</h3>
<div class="flex-container" style="display: flex; justify-content: flex-end;">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
<h3>justify-content: spece-between</h3>
<div class="flex-container" style="display: flex; justify-content: space-between;">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
<h3>justify-content: spece-around</h3>
<div class="flex-container" style="display: flex; justify-content: space-around;">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
<hr>
2. Check the result with a browser
- Open chapter15.html with a browser.
- You can see how the
justify-content
property adjusts the positions of the flex items.
You can also check the sample result here (Demo Site).