Position
Html상에 코드의 작성과 상관 없이 원하는 위치에 요소를 그려내는 css의 속성이다.
Position의 속성 값으로는 4개가 있다.
부모태그에 absolute, relative, fixed가 있으면, 자식태그는 부모태그를 참조해서 위치를 특정한다.
relative
position : relative;
로는 특별히 위치를 이동하거나 하지는 않는다.
top
, bottom
, right
, left
라는 속성을 이용해서 이동시킬 수 있다.
위의 네개의 속서은 relative가 있어야지 사용할 수 있는 속성이다.
selector {
position: relative;
}
selector {
top: -20px;
left: 30px;
}
absolute
position: absolute
절대적인 위치를 둔다. 특정부모에 대해 절대적으로 움직이게 된다.
일반적으로 absolute를 쓸 경우, 기준이 될 부모에게 position: relative;
를 부여하면 됩니다
검색창 만들기
html파일
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<input type="text" placeholder = "검색어 입력">
<img src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/icon/search.png" alt="img">
</div>
</body>
</html>
css파일
* {
box-sizing : border-box;
}
div {
position : relative;
width: 300px;
}
input {
width : 100%;
border : 1px solid #bbb;
border-radius : 8px;
padding: 10px 12px 10px 12px
}
input::placeholder{
font-size: 14px;
}
img{
position: absolute;
height: 17px;
top : 10px;
right : 12px;
margin: 0;
}
fixed
absolute, relative는 부모태그가 필요하고, 부모태그를 기준으로 삼지만,
fixed는 부모태그가 필요하지 않다.
fixed는 눈에 보이는 화면크기만큼, 화면 내에서만 움직인다.
스크롤을 내려도 fix된 위치에 고정되어서 움직이지 않는다.
html 파일
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<img src="https://www.apple.com/ac/globalnav/4/en_US/images/globalnav/apple/image_small.svg" alt="apple_img">
</header>
</body>
</html>
Css 파일
header{
position: fixed;
left: 0;
right: 0;
top : 0;
height : 48px;
background-color : rgba(45,45,45,0.95);
}
header img{
width: 20px;
height : 48px;
position : absolute;
left : 50%;
margin-left : -10px;
}