CSS

translate() center center alignment

lshjju 2026. 2. 12. 09:59

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Translate 중앙 정렬 예제</title>
    <style>
        /* 1. 화면 전체를 꽉 채우는 컨테이너 */
        .container {
            width: 100vw;
            height: 100vh;
            position: relative;
            background-color: #f8f9fa;
        }

        /* 2. 중앙에 위치할 노란 박스 */
        .yellow-box {
            width: 150px;
            height: 150px;
            background-color: #ffeb3b; /* 노란색 */
            border: 3px solid #333;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;

            /* [중앙 정렬의 핵심] */
            position: absolute;
            top: 50%;      /* 부모 높이의 50% 지점으로 이동 */
            left: 50%;     /* 부모 너비의 50% 지점으로 이동 */
            transform: translate(-50%, -50%); /* 박스 크기의 절반만큼 역이동하여 중심 보정 */
        }
    </style>
</head>
<body>

    <div class="container">
        <div class="yellow-box">중앙 박스</div>
    </div>

</body>
</html>

 

코드 동작 원리


top: 50%, left: 50%: 

박스의 왼쪽 상단 꼭짓점을 화면 정중앙에 가져다 놓습니다. (이 상태에선 박스가 우측 하단으로 쏠려 보입니다.)


translate(-50%, -50%): 

박스 자신의 너비($X$)와 높이($Y$)의 딱 절반만큼 왼쪽과 위쪽으로 끌어당깁니다. 결과적으로 박스의 정중앙이 화면의 정중앙과 일치하게 됩니다.


'CSS' 카테고리의 다른 글

transition  (0) 2026.02.15
transform  (0) 2026.02.15
CSS box model Position control steps  (0) 2026.01.26
CSS color property  (0) 2025.05.30
CSS list-style property example  (0) 2025.05.30