[HTML/CSS] div 가운데 정렬

2021. 8. 16. 17:04HTML_CSS_JS

 

▶ 해당 이미지처럼 브라우저 내 정중앙에 요소를 위치하고 싶은 경우

▶ 특정 영역(div 영역) 안에서 가운데 정렬도 가능

 

 


 

 

CSS

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

 

 

HTML+CSS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            background-color: white;
        }

        .box1 {
            position: absolute;
            width: 30%;
            height: 30%;
            background-color: skyblue;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="box1">

        </div>
    </div>
</body>

</html>

 

 

+) 특정 영역 안에서의 가운데 정렬

.container {
    position: absolute;
    width: 300px;
    height: 300px;
    background-color: black;
}

.box1 {
    position: absolute;
    width: 30%;
    height: 30%;
    background-color: skyblue;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}