flex vs margin: auto

라형선·2023년 1월 8일
0
너무 깊이 생각하실 필요는 없어요.

margin: auto는 요소를 수평 중앙보내는 역할입니다. 부모요소가 바뀌던 말던 상관없이 자기 자신이 수평중아에 가는거구요.

position을 사용하는건 부모요소를 기준으로 위치시켜야 하는 경우에 사용합니다.

만약 단순하게 요소를 수평중앙에 보내야 할 경우 position을 사용하는 것보다 그냥 margin: auto 사용하는 것이 맞습니다.

인프런 댓글

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.


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.

스택플로우

profile
형선

0개의 댓글

관련 채용 정보