HTML - Relative 와 Absolute

Jan 15, 2024
HTML - Relative 와 Absolute
 
 
지난 블로그애서는 HTML 의 position 과 관련된 내용을 다뤘다. 이번 블로그는 그 중 Relative 와 Absolute 의 관계를 보자.
 
position 과 관련된 속성은 아래의 블로그에서 확인하면 된다.
 
 
 

1. Absolute

 
Absolute 는 말 그대로 절대적인 위치다. HTML 에서 다른 요소들의 위치를 고려하지 않고 마음대로 배치가 가능하다.
 
<!DOCTYPE html> <html lang="en"> <head> <style> .box1 { width: 300px; height: 300px; background-color: yellow; display: inline-block; } .box2 { width: 300px; height: 300px; background-color: red; display: inline-block; position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
 
notion image
 
absolute 는 다른 부모 요소가 없다면 기본적으로 body 값을 따라간다. 그래서 box2 의 위치를 0px,0px 로 위치시키면 화면의 왼쪽 상단으로 이동하게 된다.
 
notion image
 
💡
노란색 박스는 따로 위치를 설정하지 않았는데 빨간색과 위치가 다르다. 이는 각 요소마다 기본적으로 상하좌우로 가지고 있는 크기가 있기 때문이다.
 
 

2. Relative 와 Absolute 관계

 
Absolute 는 Relative가 부모 요소가 되면 Relative 를 따라 위치가 정해진다.
 
<!DOCTYPE html> <html lang="en"> <head> <style> .box1 { width: 300px; height: 300px; background-color: yellow; display: inline-block; padding: relative; } .box2 { width: 300px; height: 300px; background-color: red; display: inline-block; position: absolute; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
notion image
 
위의 코드는 이런 결과가 출력된다. 이는 absolute 요소에 따로 위치를 지정하지 않으면 자동으로 static 과 동일한 위치로 가게 된다. 그래서 absolute 과 relative 의 관계를 확인하려면 부모-자식 관계로 만들어야 한다. 부모-자식 관계는 부모 태그 내부에 자식 태그를 입력하면 된다.
<body> <div class="box1"> <div class="box2"> </div> </div> </body>
 
notion image
 
이렇게 되면 absolute 는 relative 를 기준으로 위치가 정해지기 때문에 하나로 표시가 된다.
 
이제 박스들의 위치를 바꿔보자.
<!DOCTYPE html> <html lang="en"> <head> <style> .box1 { width: 300px; height: 300px; background-color: yellow; display: inline-block; position: relative; top: 100px; left: 50px; } .box2 { width: 300px; height: 300px; background-color: red; display: inline-block; position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
notion image
 
부모의 위치가 변경되니까 자식의 위치도 같이 변경이 된다.
 
💡
배치의 기본은 부모가 결정한다. 배치는 부모로부터 상대적인 위치로 결정되며, 부모가 없다면 body 를 기준으로 배치된다. 배치가 되려면 속성이 인라인 혹인 인라인-블록 속성이어야 한다. 블록은 좌우 공간 전체를 차지 하기 때문에 사용 불가하다.
Share article
RSSPowered by inblog