개발나라 스용공주

[HTML] 개체 중앙에 배치하기 / Justify-content와 align-items 본문

WEB/HTML & CSS

[HTML] 개체 중앙에 배치하기 / Justify-content와 align-items

스용공주 2024. 7. 27. 14:43
728x90
728x90

아래 사진과 같이 border로 만든 사각형을 중앙에 배치하는 방법에 대해서 알아볼 것이다.

 

우선 border를 이용하여 상자를 만들어주고 이를 감싸는 더 큰 범위의 container를 하나 생성해주었다.

<div class = "container">
            <div class = "pink">
            </div>
        </div>
.pink {
                width : 700px;
                height : 450px;
                background-color: palevioletred;
            }

 

 

그리고 중앙배치를 위해 아래 코드를 container에 만들어준다.

.container {
                display: flex;
                justify-content: center;
                align-items: center;
            }
  • display : flex : 내부에 포함된 자식 요소들을 유연하게 배치할 수 있게 해줌

 

[ justify-content : 주축 정렬 ]

  • flex-start: 자식 요소들을 컨테이너의 시작점에 정렬
  • flex-end: 자식 요소들을 컨테이너의 끝점에 정렬
  • center: 자식 요소들을 컨테이너의 중앙에 정렬
  • space-between: 자식 요소들 사이에 균등한 간격을 둠
  • space-around: 자식 요소들 주위에 균등한 간격을 둠

 

[ align-items : 교차축 정렬 ]

  • stretch: 자식 요소들을 컨테이너의 높이에 맞게 늘림 (기본값)
  • flex-start: 자식 요소들을 교차축의 시작점에 정렬
  • flex-end: 자식 요소들을 교차축의 끝점에 정렬
  • center: 자식 요소들을 교차축의 중앙에 정렬
  • baseline: 자식 요소들의 텍스트 기준선을 기준으로 정렬

 

=> container 내부에 있는 pink의 경우 container의 자식이 되기 때문에 justify-content와 align-items를 center로 설정한 뒤로 중앙 배치가 되는 것이다.

 

 

그 외에도 css 자체에 margin : 0 auto;를 주는 방법도 있다.

 

 

 

<!doctype html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8">
        <style>
            * {
                margin : 0;
                padding : 0;
            }
            h2 {
                text-align: center;
                margin : 10px;
            }
            .container {
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .pink {
                width : 700px;
                height : 450px;
                background-color: palevioletred;
            }
        </style>
    </head>
    <body>
        <h2>저녁메뉴 추천</h2>
        <div class = "container">
            <div class = "pink">
            </div>
        </div>
    </body>
</html>
728x90
728x90
Comments