simVault

G
포스트
서재
1

[css] input 박스 내 우측에 돋보기 이모지 넣는 방법, position: relative, absolute 활용

11/17/2024, 12:26:12 PM (수정: 11/17/2024, 1:47:23 PM)
htmlcss

input 박스 안 오른쪽에 돋보기 이모지를 넣는 방법에 대해 알아보도록 하겠습니다. 핵심은 css의 position: relative와 absolute를 사용하는 것입니다.

html 코드

<div class="search-container"> <input type="text" placeholder="Search..."> <span class="icon">&#x1F50D;</span> </div>

input 박스와 icon을 담을 span 요소를 모두 같은 부모 요소인 .search-container에 넣어줍니다.

css 코드

/* 검색창 컨테이너 */ .search-container { position: relative; /* 아이콘 배치를 위해 상대 위치 설정 */ width: 300px; /* 검색창 너비 */ } /* 입력 박스 스타일 */ .search-container input { width: 100%; /* 컨테이너의 전체 너비 사용 */ padding: 10px 40px 10px 10px; /* 아이콘 공간 확보 */ border: 1px solid #ccc; border-radius: 4px; font-size: 16px; outline: none; box-sizing: border-box; /* 패딩 포함한 크기 계산 */ } /* 돋보기 아이콘 스타일 */ .search-container .icon { position: absolute; top: 50%; /* 입력 박스의 세로 중앙 정렬 */ right: 10px; /* 입력 박스 오른쪽에서 10px 떨어짐 */ transform: translateY(-50%); /* 세로 중앙 정렬 보정 */ font-size: 18px; color: #555; pointer-events: none; /* 아이콘 클릭 방지 */ }

css에서 핵심적인 부분만 보충 설명을 드리겠습니다.

  • 부모 요소인 .search-container에 position 속성을 relative로 설정합니다.
  • 아이콘을 담은 .icon 요소의 position 속성은 absolute로 설정합니다.
  • input 박스 안 우측에 돋보기 아이콘이 위치하게 하기 위해서, right: 10px로 설정합니다.
  • 또한 돋보기가 input 박스의 세로 가운데에 위치하게 하기 위해서 top: 50%; transform: translateY(-50%);를 설정합니다. top: 50%으로 인해 돋보기 이모지의 윗부분이 input box의 중간 지점에 위치하게 되고, transform: translateY(-50%) 덕분에 이모지가 input box의 세로 중앙에 위치하게 됩니다.

position: relative, absolute 추가 예제

조금 더 명확한 이해를 위해 핵심 부분만 담은 예제를 하나 만들었습니다.

<!DOCTYPE html> <html> <head> <title>Page Title</title> <style> .parent { position: relative; border: 5px solid black; } .child1 { height: 200px; background-color: yellow; } .child2 { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); width: 100px; height: 100px; background-color: lightblue; } </style> </head> <body> <div class="parent"> <div class="child1"> child1 요소 </div> <div class="child2"> child2 요소 </div> </div> </body> </html>

position 예제