Question
Can I use margin: auto;
on a flex item that is being positioned with justify-content
declared on its parent flex container?
Answer
Yes! When using margin/margin-top/margin-right/margin-bottom/margin-left: auto;
on a flex item we can easily position our flex item to one side of its parent flex container:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>My Site - Flexbox</title>
</head>
<body>
<nav>
<div>1</div>
<div>2</div>
<div>3</div>
<div class="four">4</div>
</nav>
</body>
</html>
CSS:
nav {
display: flex;
border: 1px solid black;
}
div {
width: 100px;
height: 50px;
border: 1px solid blue;
}
.four {
margin-left: auto; /*.four <div>'s left margin will take up all available space, pushing the div all the way to the right end of the flex container*/
}
We can also center a flex item:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>My Site - Flexbox</title>
</head>
<body>
<section>
<div></div>
</section>
</body>
</html>
CSS:
section {
display: flex;
border: 1px solid black;
height: 300px; /*height added to show that `margin: auto;` will calculate both horizontal and vertical margins, if no height were added, `margin: auto;` would calculate horizontal margin*/
}
div {
width: 100px;
height: 50px;
border: 1px solid blue;
margin: auto; /*calculates `margin-top/bottom` and `margin-right/left` so the space is evenly distributed on top/bottom and left/right (respectively) of item*/
}
Note: in both examples we are using the default justify-content: flex-start;
declaration