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

a 夏天 提交于 2019-11-27 07:45:00

问题


To center both horizontally and vertically simultaneously, there are two simple options:

First

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

Second

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

What's the difference? In what situations would we use one over the other?


回答1:


In your first example...

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

... the auto margin applies only to the flex item and centers that one flex item within the container.

In your second example...

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

You are centering items from the container level. This code will center all items.

Also, keep in mind, if you use both methods at the same time, margin: auto should prevail.

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension

If free space is distributed to auto margins, the alignment properties will have no effect in that dimension because the margins will have stolen all the free space left over after flexing.

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

To overcome this problem, use margin: auto for centering to work properly.

Here's a more complete explanation:

  • Can't scroll to top of flex item that is overflowing container
  • Center a flex item vertically and horizontally (see Box #56)

IE Bugs:

  • Flex auto margin not working in IE10/11
  • Flexbox auto margins don't work with justify-content: center in IE


来源:https://stackoverflow.com/questions/44244549/whats-the-difference-between-marginauto-and-justify-content-align-items-cent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!