[CSS] Position 속성

JunHyeok Seo·2023년 9월 9일

web

목록 보기
3/9

Position 속성

CSS에서 position 속성은 HTML 문서 상에서 요소가 배치되는 방식을 결정한다. 많은 경우, position 속성은 요소의 정확한 위치 지정을 위해서 topleftbottomright 속성과 함께 사용된다.****

position: static

기본값

position 속성이 static인 요소는 HTML 문서 상에서 원래 있어야하는 위치에 배치

topleftbottomright 속성값은 position 속성이 static일 때는 무시

position: relative

요소를 원래 위치에서 벗어나게 배치할 수 있다

원래 위치를 기준으로 상대적(relative)으로 배치

topbottomleftright 속성을 이용할 수 있다

position: absolute

position 속성이 absolute일 때 해당 요소는 배치 기준을 자신이 아닌 상위 요소에서 찾는다.

DOM 트리를 따라 올라가다가 position 속성이 static이 아닌 첫 번째 상위 요소가 해당 요소의 배치 기준으로 설정된다. 만약에 해당 요소 상위에 position 속성이 static이 아닌 요소가 없다면, DOM 트리에 최상위에 있는 <body> 요소가 배치 기준이 된다.

실제 absolute 속성값을 사용할 때 이러한 복잡한 특성을 활용하는 경우는 드물다. 대부분의 경우, 부모 요소(가장 가까운 상위 요소)를 기준으로 topleftbottomright 속성을 적용한다.

CSS의 position 속성으로 HTML 요소 배치하기

<!DOCTYPE html>
<html>
<head>
    <title>Absolute Position</title>
    <style>
        /* 초기화 */
        * { margin: 0; padding: 0; }

        /* 주제 */
        body { background: red; }
        #container {
            /* 색상 및 크기 적용 */
            width: 500px; height: 250px;
            background: orange;

            /* 위치 설정 */
            position: absolute;
            left: 50%; top: 50%;
	        /*
	        요소의 시작점. 즉, 좌측 상단 모서리가 중앙에 위치
	        따라서 현재 container 스타일일 적용될 블럭의 중앙값을 margin으로 설정
	        */
            margin-left: -250px;
            margin-top: -125px;
        }
    </style>
</head>
<body>
    <div id="container">
        <h1>요소의 중앙 배치</h1>
    </div>
</body>
</html>

0개의 댓글