Margin auto doesn't align in horizontal center

Hi, This is the live link.

.prevnext {
  border: 2px solid navy;
  /*margin: auto;*/
  display: flex;
  justify-content: space-between;
}
.prevnext a {
  display: block;
  color: #E22658;
  text-transform: uppercase;
  text-align: center;
  font-size: 1rem;
  font-weight: bold;
  border: 2px solid #E22658;
  border-radius: 20px;
  max-width: 200px;
  padding: 10px 20px;
  text-decoration: none;
  border-bottom: 4px solid #E22658;
}

I fail to position this in horizontal center →

When I activate margin: auto then it starts to chip in those two anchor texts.
Where I am faltering?

Is this any conflict of CSS or certain gap in my understanding?

You need width:100% on the element prevnext.

.prevnext{width:100%;}

You already have a max-width so the margin:auto will center the element.

When you add margin :auto to the flex element it pushes its left edge away from whatever is at that side and vice-versa. auto margins on flex and flex-items are powerful tools.

2 Likes

Hi, there @PaulOB So this was not a nice approach or right way?

I didn’t get it? Do you have any codepen where you used or demonstrated this distinction?

I’ll put up a demo later when I get back to my computer. :slight_smile:

1 Like

The element you apply margin:auto has a display of flex applied but itself is already a flex-item. Auto margins on flex-items will push the element away from the sides. A flex item does not have a specific width unless you give it one, or it has content width or you make it grow etc.

This is compounded in your example because there are two parents of display:flex (both of which are not needed) meaning that flex-items are within flex-items so their width may be controlled by the largest content

If you remove display:flex from .wrapper and from .bcontent then the margin:auto will work on .prevnext as normal because it is no longer a flex-item. Or as I suggested force a width on prevnext instead.

The main takeaway is that you don’t add flex to wrappers where you are not using the flex properties for layout. There’s no need and you make it harder for yourself when you have to remember that a flexbox is also a flexitem and will be affected by flex-item properties.

You can see your set up in the first example here along with some simple demos.

All can be avoided by not nesting the flexbox unless you have to. When you nest a flexbox remember that its width may not be what you expect and auto margins will work differently.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.