디지털 컨버전스/HTML&CSS

[CSS] 수직 정렬 - transform:translate()

gimyeondong 2020. 4. 7. 12:24

 

수직정렬

1) line-height : 텍스트이며 1줄인경우

2) transform: translate(50%, 50px) : transform이 적용되는 Element의 크기 기준 %

 

부모 요소 사이즈가 변해도 정렬이 되도록

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            *{box-sizing: border-box;}
            div{border: 1px solid black;}
            .wrapper{
                width: 300px; 
                height: 300px; 
                line-height: 300px;
                position: relative
                
            }
            .box{
                width: 100px;
                height: 100px;
                position: absolute;
                top: 50%;
                left:50%;
            }
        </style>

    </head>
    <body>
        <div class="wrapper">
            <div class="box"></div>
        </div>
    </body>
</html>

왼쪽 위 모서리 기준으로 중앙으로 이동

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            *{box-sizing: border-box;}
            div{border: 1px solid black;}
            .wrapper{
                width: 300px; 
                height: 300px; 
                line-height: 300px;
                position: relative
                
            }
            .box{
                width: 100px;
                height: 100px;
                position: absolute;
                top: 50%;
                left:50%;
                transform: translate(-50%,-50%)
            }
        </style>

    </head>
    <body>
        <div class="wrapper">
            <div class="box"></div>
        </div>
    </body>
</html>

transform:translate(-50%,-50%) 자체 사이즈 만큼 이동