[CSS] position

Happhee·2022년 1월 22일
0

HTML + CSS

목록 보기
7/7

문서상에 요소를 배치하는 방법인 position에 대해 알아보자


relative vs static

position의 기본값은 static이며, 위치와 관련된 설정을 하지 않는 상태를 의미한다.
relative로 설정하면, 부모 요소에 대한 요소 크기의 설정값인 offset을 가질 수 있게된다.

<html>
  <head>
    <style>
        html{border:1px solid gray;}
        div{
            border:5px solid tomato;
            margin:10px;
        }
        #me{
            position: relative;
            left:100px;
            top:100px;
        }
    </style>
  </head>
  <body>
    <div id="other">other</div>
    <div id="parent">
       parent
       <div id="me">me</div>
    </div>
  </body>
</html>

상대적인것은 부모를 기준

absolute

기준이 html 절대적인 위치에 생성된다 (left, top이 모두 0이고, 부모요소의 position이 static일때만)
해당 요소는 더이상 부모의 소속아니다

크기를 지정해주고 싶다면 width를 사용해야한다

<html>
  <head>
    <style>
        #parent, #other, #grand{
            border:5px solid tomato;
        }
        #grand{
            position: relative;
        }
        #me{
            background-color: black;
            color:white;
            position: absolute;
            left:0;
            top:0;
        }
    </style>
  </head>
  <body>
    <div id="other">other</div>
    <div id="grand">
       grand
        <div id="parent">
           parent
           <div id="me">me</div>
        </div>
    </div>
     
  </body>
</html>

부모중에 position type이 지정된 부모를 기준으로 놓여진다

fixed

화면의 절대적인 위치에 고정시켜서 스크롤을 무시한다.
크기를 지정하기 위해서 width, height를 지정해주어야 한다

<html>

<head>
    <style>
        body {
            padding-top: 30px;
        }

        #parent,
        #other,
        #grand {
            border: 5px solid tomato;
        }

        #grand {
            position: relative;
        }

        #me {
            background-color: black;
            position: fixed;
            width: 100%;
            height: fit-content;
            left: 0;
            top: 0;
        }

        #me p {
            color: white;
            text-align: center;
            font-size: 10px;
            height: fit-content;
        }

        #large {
            background-color: pink;
            height: 100%;
        }
    </style>
</head>

<body>
    <div id="other">other</div>
    <div id="parent">
        parent
        <div id="me">
            <p>타이틀</p>
        </div>
    </div>
    </div>
    <div id="large">large</div>
</body>

</html>

profile
즐기면서 정확하게 나아가는 웹프론트엔드 개발자 https://happhee-dev.tistory.com/ 로 이전하였습니다

0개의 댓글