What's the difference between margin: auto and align-content / align items?

To center both horizontally and vertically at the same time, there are two simple options:

The first

.outer {
  display:flex;
}
.inner {
  margin:auto;
}

      

Second

.outer {
  display: flex;
  justify-content: center;
  align-items: center;
}

      

Who cares? In what situations will we use one over the other?

+3
html css flexbox css3 centering


source to share


2 answers


In the first example ...

.outer {
  display: flex;
}
.inner {
  margin: auto;
}

      

... the marker auto

applies only to the flex item and centers that one flex item in the container.

In your second example ...

.outer {
  display: flex;
  justify-content: center;
  align-items: center;
}

      

You center the elements from the container level. This code will center all elements.

Also, keep in mind that if you are using both methods at the same time, margin: auto

should prevail.



8.1. Align with auto margin

Before aligning through justify-content

and align-self

, any positive white space is propagated to the automatic margins at that size

If the free space extends to automatic margins, then the alignment properties will have no effect in that dimension, since the margins will have stolen all of the free space after folding.

But the most important difference for practical purposes may be the behavior when the flex item exceeds the container size. When this happens, you lose access to parts of the element when using container-level code. The item disappears from the screen and is not available by scrolling.

To fix this problem, use the margin: auto

center to work properly.

Here's a more complete explanation:

  • Unable to scroll to the top of flex item that overflows container
  • Center the slender vertically and horizontally (see box 56).

IE Errors:

  • Flex auto margin not working in IE10 / 11
  • Flexbox auto margins not working with justify-content: center in IE
+6


source to share


.outer {
  display: flex;
  justify-content: center;
  align-items: center;
}

      

I use this in situations where I need the alignment to differ across different screen sizes.



@media max-width: 768px{
.outer {
  justify-content: flex-end;
}
}

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics