본문 바로가기

CSS

[CSS] margin으로 가운데 정렬

간단하게 가운데 정렬을 쉽게 할 수 있는 방법이 있습니다

 

바로 예를 들어 보자면

 

아래 box를 만들었습니다

 

<body>
  <div class="box">box</div>
</body>
.box {
  width: 300px;
  height: 300px;
  background-color: royalblue;
}

왼쪽 상단에 box가 위치해 있습니다 여기서 margin을 통해 간단하게

body요소의 흐름에 따라 가운데 정렬을 할 수가 있습니다

 

margin: 0px auto;
.box {
  width: 300px;
  height: 300px;
  background-color: royalblue;
  margin: 0px auto;
}

body가 상위요소가 아닌 부모 요소를 하나 만들어 가로(width)를 설정해주고 만들어 보겠습니다

<body>
  <div class="box-pack">
    <div class="box">box</div>
  </div>
</body>
body {
  background-color: bisque;
}

.box-pack {
  width: 1000px;
  background-color: aquamarine;
}
.box {
  width: 300px;
  height: 300px;
  background-color: royalblue;
  margin: 0px auto;
}

이렇게 되면 부모요소인 box-pack의 1000px만큼의 영역에서 margin을 자동으로 정렬하여 가운데 배치합니다