CSS justify-content explained
CSS Detailed explanation of justify-content
What is justify-content?
In CSS, justify-content
is used to define how the browser distributes extra space (i.e., white space on the main axis) between child elements. For example, in a flex container, when the main axis space is greater than the combined widths of all child elements, the justify-content
property determines how the child elements are aligned.
Optional Values
justify-content
has the following optional values:
flex-start
: Default value, aligns child elements at the start of the main axis.flex-end
: aligns child elements at the end of the main axis.center
: aligns child elements at the center of the main axis.space-between
: distributes child elements evenly along the main axis, leaving no gaps between them.space-around
: distributes child elements evenly along the main axis, leaving equal gaps between them and the container’s edges.space-evenly
: The child elements are evenly distributed along the main axis, with equal space at the beginning, end, and sides.
How to Use justify-content
The justify-content
property is commonly used in flex layouts. Here’s a simple example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flex Layout</title>
<style>
.container {
display: flex;
justify-content: space-between;
}
.item {
width: 100px;
height: 100px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>
In this example, we create a flex container .container
that contains three child elements .item
. We use justify-content: space-between;
to evenly distribute the child elements along the main axis.
Sample Code Results
If you open this sample code in a browser, you’ll see three equal-width gray squares evenly spaced within the flex container.
Real-World Examples
In practice, the justify-content
property can help us achieve a variety of layout effects. Here are some examples:
Center Alignment
<style>
.container {
display: flex;
justify-content: center;
}
</style>
This code centers the child elements along the main axis.
Justify
<style>
.container {
display: flex;
justify-content: space-between;
}
</style>
This code distributes the child elements on both ends of the main axis, leaving no space between them.
Evenly distributed
<style>
.container {
display: flex; justify-content: space-around;
}
</style>
This code evenly distributes child elements along the main axis, with equal spacing between the container’s edges.
Summary
The justify-content
property is very useful in flex layout. By adjusting its value, we can easily achieve various layout effects. In practical applications, choosing the appropriate justify-content
value based on your needs can make your page layout more beautiful and flexible.