Can I use margin: auto; on a flex item that is being positioned with justify-content declared on its parent flex container?

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

1 Like

Thanks for this but I cannot see the justify-content declaration anywhere in this code. Can you explain this? Thanks.

1 Like

I believe display: flex; is equivalent to justify-content: flex-start; because flex-start is the default value.

10 Likes

This is the screenshot of what I can see after running the second set of HTML and CSS codes. Is it supposed to appear like this?

1 Like

It’s been a few weeks since you commented, so you probably already found an answer.

According to the comments in the CSS code, I believe that is the way it’s expected to appear. Since the parent element (section) has a defined height (300px), the “auto” margin of the div element will add space on all four sides (not just left and right). So it is centered horizontally and vertically.

3 Likes