Stack/CSS

[CSS] 원하는 요소 중앙에 배치하는 방법

7ingout 2022. 4. 13. 16:58

position을 이용해 요소의 중앙에 배치하기

1. top: 50% / left: 50% / transform: translate(-50%, -50%)

 

2. top: 50% / left: 50%

margin-left: -50px; 쌤이 여기 왜 -50이라 적으셨을까

margin-top: -100px;

 

3. calc()함수를 사용

calc(50% - 100px)

초록 부분 띄어쓰기 필수 ! 띄어쓰기 안하니까 안되넹

 

<!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>
        body > div {
            width: 1000px;
            height: 600px;
            background: lightcoral;
            margin: 0 auto;
            position: relative;
        }
        div div {
            width: 300px;
            height: 200px;
            background: darkblue;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>
    <div>
        <div></div>
    </div>
</body>
</html>