다연이네

[days02] 위치 속성(position) 본문

Web/CSS

[days02] 위치 속성(position)

 다연  2020. 12. 4. 19:18
반응형

 css 위치(position) 속성  => 레이아웃 잡을때 많이 사용 잘봐두자


- static   기본값(정적 배치) - top, bottom, left, right 속성의 영향을 받지 않는다.
- relative  상대좌표, [다른 요소들은 간격이 조정되지 않는다.]
- fixed  고정(뷰포트를 기준으로 배치된다. 스크롤되더라도 항상 같은 위치에 유지된다.)
- absolute  절대좌표(가장 가까운 위치의 조상을 기준으로 배치된다)
- sticky  사전적 의미(끈적끈적)  ->사용자의 스크롤 위치에 따라 배치

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<style>
	div.static{
	position: static;
	left:100px; /* 의미없음 적용안됨 */
	}
	
	hr{
	 border: 1px solid red;
	 padding: 0;
	}
	
	div{
		border: 1px solid gray;
		width: 100px;
		height: 100px;
		text-align: center;
	}
	
	div:first-child {
	background-color: red;
}
/* 	div:nth-child(2) {
	background-color: green;
	position: relative; 
	포지션을 relative로 주고 left, right, top, bottom을 설정하지 않으면 그냥 static과 동일 
	left:20px;
	top:20px;
}	 */


	div:nth-child(2) {
	background-color: green;
	position: absolute; /* 얘만 줬는데 box3이 사라짐 (box2밑에 숨겨짐) */
	/* absolute 주면 위로 떠오르기 때문, left, right 안주니까 그냥 원래 그자리 그대로 있음 */
	/* left:300px; */
	right:50px; /* 우측기준 */
	top:0; /*값 주면 자리 이동 */
	
}	

	div:nth-child(3) {
	background-color: blue;
	/* position: fixed;  relative랑 겹치면 걔보다 위로 올라옴  
	right:5px;
	bottom: 10px;
	border-radius: 50px; */ /* 원을 그린게 아니라 사각형을 라운드 준 것 */
}	
	
	
</style>

</head>
<body>

<div>box1</div>
<div>box2</div>
<div>box3</div>


hello world <span>admin</span> <!-- span태그는 인라인이라 그 위치에 그냥 찍힘 -->
<div class="static">Lorem ipsum dolor sit amet.</div>
</body>
</html>

 

 

문제) position을 사용해서 해당 박스 위치 옮기기 

빨강 박스는 왼쪽20px, 위20px으로

파랑 박스는 오른쪽20px, 위20px로 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<style>

div{
border: 1px solid gray;
width: 80%;
height: 100px; 
}


div:first-child {
	
}

#fir{
	border: 1px solid red;
	width:50px;
	height: 50px;

}
#sec{
	border: 1px solid blue;
	width:50px;
	height: 50px; 

}

</style>


</head>
<body>
<div></div>

<div>
<div id="fir">in</div>
<div id="sec">in</div>
</div>
<div></div>
</body>
</html>

해당 코드에서 수정할 부분

스타일에서
#fir{
	border: 1px solid red;
	width:50px;
	height: 50px;
	
	position: absolute;
	left: 20px;
	top: 20px;
}
#sec{
	border: 1px solid blue;
	width:50px;
	height: 50px; 
	
	position: absolute;
	right: 20px;
	top: 20px;
}


바디에서
<div style="position: relative;">

조상(div)에서 positon을 relative (또는 absolute도 가능하나, 그러면 밑에 있는 박스가 위로 딸려올라와 숨는다)로 지정한 다음, 빨강박스로 가서 position을 absolute로 지정한다.

absolute는 가까운 조상을 기준으로 잡기 때문에, 조상의 크기가 변하면(화면을 늘리거나 줄이거나) 그에따라 해당 박스의 위치도 변하기 때문에 좋은 코딩으로 볼 수 있다.

반응형
Comments