Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS justify-content: flex-end로 플렉스 항목을 컨테이너 끝에 정렬하는 방법

CSS에서 플렉스 항목(flex item)을 컨테이너의 끝에 정렬하려면 justify-content 속성에 flex-end 값을 사용합니다. 이 속성은 플렉스 컨테이너의 주축(main axis) 방향으로 항목들을 어떻게 배치할지 결정하며, flex-end를 지정하면 모든 항목이 컨테이너의 끝부분(기본 설정 기준 오른쪽)으로 몰려 정렬됩니다.

예제

아래 코드를 실행하면 flex-end 값이 실제로 어떻게 동작하는지 확인할 수 있습니다.

<!DOCTYPE html>
<html>
   <head>
      <style>
         .mycontainer {
            display: flex;
            background-color: red;
            justify-content: flex-end;
         }
         .mycontainer > div {
            background-color: #E6B0AA;
            text-align: center;
            line-height: 60px;
            font-size: 30px;
            width: 100px;
            margin: 5px;
         }
      </style>
   </head>
   <body>
      <h1>Score</h1>
      <div class = "mycontainer">
         <div>20</div>
         <div>35</div>
         <div>88</div>
         <div>62</div>
      </div>
   </body>
</html>

코드 설명

.mycontainer 클래스에 display: flex;를 적용해 플렉스 컨테이너를 만들고, 여기에 justify-content: flex-end;를 추가하여 자식 요소들을 컨테이너의 끝으로 정렬했습니다. 코드를 실행하면 빨간색 컨테이너 안에서 네 개의 숫자 항목(20, 35, 88, 62)이 왼쪽이 아닌 오른쪽 끝에 붙어 배치되는 것을 확인할 수 있습니다.

참고로 justify-content 속성에는 flex-start(시작 부분 정렬), center(가운데 정렬), space-between(양 끝 정렬 후 균등 분배), space-around(균등한 여백 분배) 등 다양한 값을 사용할 수 있으므로, 상황에 맞게 활용하면 됩니다.