본문 바로가기

HTML & CSS

CSS - position property

css에서 selector의 property로 줄 수 있는 position에는 대표적으로 4가지 값이 있다.

1. static

기본값. 코드 순서대로 보여준다.

2. relative

top, right, bottom, left property를 반드시 사용해 원래 위치에서 상대적으로 그만큼 움직인다.

3. absolute

부모 요소에 대해 그 property 값과 같은 절대적인 위치를 가진다. top, right, bottom, left property를 이용한다.

부모 요소는 반드시 position 값을 갖고 있어야 되며, 일반적으로 relative를 부여한다.

원하는 결과

 

<!-- html body -->

<div class="relative">
      <input type="text" placeholder="검색어 입력">
      <img class="absolute" src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/icon/search.png">
</div>

돋보기 이미지를 input box 안에 배치하고자 한다. 부모 요소가 되는 div에 relative를 주고 img에 absolute를 넣어 div 안에서 원하는 위치에 고정 시킨다.

/* css */

* {
  box-sizing: border-box;
}

.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

input {
  width: 100%;
  border: 1px solid #bbb;
  border-radius: 8px;
  padding: 10px 12px;
  font-size: 14px;
}

div {
  width: 300px;
}

img {
  width: 17px;
  top: 10px;
  right: 12px;
}

div에 width를 넣고 input에 width 100%를 넣어 input box의 사이즈를 조정했다.

4. fixed

window 기준으로 고정한다. top, right, bottom, left property를 이용한다.

원하는 결과

<!-- html body -->

<header>
      <img width="20px" height="48px" 
      	src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/icon/search.png">
</header>

페이지 맨 위에 고정되어 있는 헤더를 만들고자 한다. 

/* css */

header {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  height: 48px;
  background-color: rgba(247, 194, 194, 0.95)
}

img {
  width: 20px;
  height: 20px;
  position: absolute;
  top: 50%;
  margin-top: -10px;
  left: 50%;
  margin-left: -10px;
}

스크롤하면 body에 있는 다른 content들이 헤더 뒤로 지나간다. 최초 화면에서 맨 위에 있는 content가 헤더 뒤로 가려지지 않게 하려면 body에 padding-top: 48px;을 추가해야 된다.

'HTML & CSS' 카테고리의 다른 글

CSS - float property  (0) 2021.01.12
CSS - display property  (0) 2021.01.12
Semantic Web, Semantic Tag  (0) 2021.01.11
HTML, CSS 꾸미기  (0) 2020.12.19
HTML, CSS  (0) 2020.12.19