농장/HTML5·CSS

[CSS] position : relative, absolute +중앙정렬하기

귤발자 2020. 3. 31. 16:01
728x90
반응형
<!Doctype html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  right: 50px;
  top : 50px;
  position: absolute;
  background: red;
}
</style>
<body>

<h2>My First JavaScript Animation</h2>

<div id="container">
<div id="animate"></div>
</div>

</body>
</html>

 

 

<!Doctype html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  /*position: relative;*/
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  right: 50px;
  top : 50px;
  position: absolute;
  background: red;
}
</style>
<body>

<h2>My First JavaScript Animation</h2>

<div id="container">
<div id="animate"></div>
</div>

</body>
</html>
 

출처: https://www.w3schools.com/

추가로 참고하면 좋은 글: https://rgy0409.tistory.com/2951

 

※ 주의할 점. absolute 속성은 inline이 아닌 div와 같은 블럭 element에 지정해야 작동함. 버튼에 absolute 지정해도 안먹힘.

 


 

absolute속성에서 중앙정렬하기(CSS)

 

1. 수직과 수평에 대해 중앙정렬

position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);

 

2. 수직에 대해 중앙정렬

top: 50%; 
transform: translate(-50%);

 

3. 수평에 대해 중앙정렬

left: 50%; 
transform: translate(-50%);

 

 

728x90
반응형