Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS로 이미지 위에 버튼을 추가하는 방법

웹 페이지에서 이미지 위에 버튼을 배치하면 클릭 유도(CTA) 요소를 효과적으로 강조할 수 있습니다. CSS의 position 속성과 transform 속성을 활용하면 이미지 중앙에 버튼을 손쉽게 배치할 수 있습니다.

CSS로 이미지에 버튼 추가하기

다음은 CSS를 사용하여 이미지 위에 버튼을 추가하는 전체 코드입니다.

예제 코드

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img{
    width: 100%;
}
div {
    position: relative;
    width: 100%;
    max-width: 400px;
}
div img {
    width: 100%;
    height: auto;
}
div button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgb(64, 21, 133);
    color: white;
    font-size: 20px;
    padding: 24px 36px;
    width: 220px;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    text-align: center;
    font-weight: bolder;
    font-family: monospace,sans-serif,serif;
}
div button:hover {
    color:yellow;
}
</style>
</head>
<body>
<h1>Button on Image Example</h1>
<div>
<img src="https://i.picsum.photos/id/354/400/400.jpg">
<button class="btn">Button</button>
</div>
</body>
</html>

핵심 포인트 정리

  • position: relative — 부모 요소인 div에 적용하여 버튼 배치의 기준점을 만듭니다.
  • position: absolute — 버튼을 부모 요소 기준으로 자유롭게 배치합니다.
  • top: 50%; left: 50% — 버튼을 이미지의 정중앙 위치로 이동시킵니다.
  • transform: translate(-50%, -50%) — 버튼 자체의 크기만큼 보정하여 완벽하게 가운데 정렬합니다.

실행 결과

위 코드를 실행하면 이미지 중앙에 보라색 버튼이 배치된 화면이 출력됩니다.

마우스 오버(hover) 효과

버튼에 마우스를 올리면 :hover 선택자에 의해 글자 색상이 노란색으로 변경됩니다. 이처럼 hover 효과를 활용하면 사용자에게 시각적인 피드백을 제공하여 인터랙티브한 UI를 만들 수 있습니다.