본문 바로가기

[JS] 두개의 이미지를 겹쳐서 놓고싶을때, Position

I'm 영서 2024. 7. 17.
반응형

열심히 프로젝트를 만드는데, 

 

두개 혹은 여러개의 tag를 겹쳐서 놓아야 할 때 가 있다. 

 

예를들면 아래와 같은경우.. img위에 img나 btn등이 들어갈때가 있는데 

 

이때 써야하는건 position을 사용하는거다. 

 

 

position : static

 

position : fixed

position : fixed는 요소를 브라우저 기준으로 배치한다. 

스크롤을 해도 항상 같은곳에 요소가 위치한다. 보통 네비게이션 바에 사용하는데, 엑셀등에 있는 틀 고정을 생각하면 편하다.

position : sticky

position : sticky는 요소가 스크롤을 따라 움직이다가, 특정 지점에 도달하면 고정된다. 



position : relative

 position : relative는 요소를 문서 흐름에 맞게 배치하되, 자신의 위치를 기준으로 offset을 줄 수 있게 해준다. 

쉽게생각하면 하위 객체들에 대해 absolute의 범위를 position : relative 태그를 가진 객체로 지정하는것이다.

position : absolute

position : absolute는 요소를 문서 흐름에서 제거하고, 가장 가까운 position : relative , position : absoulte, fiexed인 조상 요소를 기준으로 배치한다. 그런 요소가 없다면 초기 블록 <html> , <body> 태그에 붙는다.

 

 

이를 바탕으로 위에 이미지에 나온 이미지 위에 btn을 추가하는 방법은 아래와 같다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Position Example</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        .container {
            position: relative;
            width: 500px;
            height: 300px;
        }
        .background {
            width: 100%;
            height: auto;
        }
        .overlay {
            position: absolute;
            top: 20px;
            left: 20px;
            width: 100px;
            height: auto;
        }
        .overlay-btn {
            position: absolute;
            top: 100px;
            left: 20px;
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <img src="" alt="Background Image" class="background">
        <img src="" alt="Overlay Image" class="overlay">
        <button class="overlay-btn">Click Me</button>
    </div>
</body>
</html>
반응형

댓글