-
position 문제프론트엔드/CSS 2023. 7. 4. 21:01728x90
Why does absolute positioned element is displayed over a static one?
I know absolute positioning breaks normal flow but since the order in HTML is absolute element first then static one, I was expecting it to be reflected in the display order too. .absolute {
stackoverflow.com
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>자바스크립트 연습</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div class="img">이미지</div> <div class="text">텍스트</div> </div> <script src='app.js'></script> </body> </html>
body{ margin: 0; padding: 0; } .container{ width: 100%; height: 100vh; background-color: bisque; } .img, .text{ text-align: center; line-height: 300px; font-size: 10rem; color: white; } .img{ width: 50%; height: 300px; margin: 0 auto; background-color: aquamarine; } .text{ width: 70%; height: 300px; margin: 0 auto; background-color: springgreen; }
컨테이너 안에는 이미지와 텍스트 요소가 화면처럼 위치하고 있다.
이때 컨테이너에 position: relative 이미지에 position: absolute 로 설정하면 어떻게 될까?
body{ margin: 0; padding: 0; } .container{ width: 100%; height: 100vh; background-color: bisque; position: relative; } .img, .text{ text-align: center; line-height: 300px; font-size: 10rem; color: white; } .img{ width: 50%; height: 300px; margin: 0 auto; background-color: aquamarine; position: absolute; } .text{ width: 70%; height: 300px; margin: 0 auto; background-color: springgreen; }
이미지가 텍스트 요소를 가려버린다. 이유는 css 규칙에 의하여 absolute 로 설정된 요소는 static 요소 위에 그려진다.
그럼 텍스트 요소를 이미지 위에 보이게 하려면 어떻게 하면 될까?
body{ margin: 0; padding: 0; } .container{ width: 100%; height: 100vh; background-color: bisque; position: relative; } .img, .text{ text-align: center; line-height: 300px; font-size: 10rem; color: white; } .img{ width: 50%; height: 300px; margin: 0 auto; background-color: aquamarine; position: absolute; } .text{ width: 70%; height: 300px; margin: 0 auto; background-color: springgreen; position: relative; }
텍스트 요소에 position: relative 를 적용하면 된다. 이렇게 하면 absolute 와 relative 는 같은 레벨이 되며 문서 흐름에 따라 나중에 작성된 텍스트가 나중에 렌더링된다.
728x90'프론트엔드 > CSS' 카테고리의 다른 글
SASS 입문 (0) 2023.07.17 부트스트랩 5 자주 쓰는 클래스 정리 (0) 2023.07.14 table table-cell 속성을 이용하여 수평으로 나열하기 (0) 2023.06.24 자바스크립트 없이 탭메뉴 만들기 (0) 2023.06.23 우주의 공전 궤도 그리기 (0) 2022.07.15