본문 바로가기

TroubleShooting/CSS

[CSS] margin: 0 auto 중앙 정렬이 작동하지 않는 경우

 

필수 조건은 아래 두개를 만족해야 합니다.

 

1. 블록 레벨 요소여야 함 (display: block, grid, flex 등)
2. 너비가 지정되어 있어야 함 (width, max-width)

 


 

 

대표적으로 작동하지 않는 케이스들입니다

 

1. position: absolute 또는 fixed 가 아니여야 합니다.

(일반적인 문서 흐름에서 요소를 제거하기 때문)

 

<style>
/* 방법 1: left, transform 사용 */
.element1 {
  position: absolute;
  width: 200px;
  left: 50%;
  transform: translateX(-50%);
}

/* 방법 2: left, right 사용 */
.element2 {
  position: absolute;
  width: 200px;
  left: 0;
  right: 0;
  margin: 0 auto;
}
</style>

 

 

2.float 속성이 적용된 경우

<style>
.element {
  float: left; /* 또는 right */
  width: 200px;
  margin: 0 auto; /* 작동하지 않음 */
}
</style>

 

 

3.부모 요소에 display: flex가 적용된 경우

<style>
.parent {
  display: flex;
}
.child {
  width: 200px;
  margin: 0 auto; /* 작동하지 않음 */
}
/* 대신 부모에 justify-content: center; 사용 */
</style>

 

 

4.transform 속성이 적용된 경우

<style>
.element {
  width: 200px;
  transform: scale(1.2);
  margin: 0 auto; /* 예상대로 작동하지 않을 수 있음 */
}
</style>

 

 

5. calc()로 동적 너비가 설정된 경우

<style>
.element {
  width: calc(100% - 20px);
  margin: 0 auto; /* 의도한대로 작동하지 않을 수 있음 */
}
</style>