position으로 요소의 위치를 조정

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="css/position.css">
  <title>Document</title>
</head>
<body>
  <div class="a">a</div>
  <div class="b">b</div>
  <div class="c">c</div>
  <div class="d">d</div>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</body>
</html>

 

- position: static : 요소들의 자연스러운 흐름에 따라 원래 있을 자리에 배치, 기본값, 지정하지 않으면 그냥 이 상태임

- position: relative : 원래 있을 위치의 좌상단을 기준으로 이동

- position: absolute : 브라우저 화면의 좌상단을 기준으로 이동

- position: fixed : Scroll을 해도 항상 지정된 위치에 고정되어 있음, fixed의 경우, 위치 이동은 absolute처럼 적용됨

- position: sticky : 평소에는 static처럼 있다가 Scroll들의 화면 변화에 따라 지정된 위치에 고정됨

- left, top, bottom, right : 움직일 값 입력

- z-index : 요소들간의 z 축, 요소들끼리 겹치는 경우 위에 있을 요소를 결정함, static이 아닌 요소에 적용 가능

- 기본적으로 static이 아닌 요소가 static요소보다 위에 위치하고, 동등할 경우 나중에 나오는 요소가 위에 위치함

body {
  height: 10000px;
}

div {
  display: inline-block;
  width: 200px;
  height: 200px;
  opacity: 0.7;
}
.a {
  background: red;
}
.b {  
  position: relative;
  left: -60px;
  top: 10px;  
  z-index: 999;
  background: green;
}
.c {  
  position: absolute;
  left: 20px;
  top: 50px;
  background: blue;
}

.d {  
  position: fixed;
  left: 30px;
  top: 100px;
  background: orange;
}
p {  
  position: sticky;
  top: 50px;
  background: skyblue;
}


position설정시 부모요소와 자식요소 간의 관계

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="css/position.css">
  <title>Document</title>
</head>
<body>
  <div class="parent">
    <div class="child">
    </div>
  </div>
</body>
</html>

- 기본적으로 positon: absolute면 브라우저의 좌상단을 기준으로 움직이지만,

  부모요소가 static만 아니면, 자식에 positon: absolute를 지정하는 경우, 부모의 좌상단을 기준으로 움직임

 

- 부모가 position: fixed면 자식도 같이 고정됨

body {
  height: 10000px;
}

div {  
  display: inline-block;
  width: 200px;
  height: 200px;
}
.parent {
  /* position: fixed; */
  position: relative;
  left: 100px;
  top: 100px;
  z-index: 999;
  background: green;
}
.child {
  position: absolute;
  left: 50px;
  top: 10px;
  width: 50px;
  height: 50px;
  background: red;
}

'WEB > css' 카테고리의 다른 글

[CSS] flex  (0) 2020.04.12
[CSS] 가로배치방법 (display: inline-block, float: left)  (0) 2020.04.12