클릭하면 색상이 바뀌는 버튼 만들기|CSS & JavaScript 실습 예제

버튼을 클릭했을 때 색상이 자연스럽게 바뀌는 인터랙티브 UI를 구현해보세요. CSS 트랜지션과 JavaScript 클릭 이벤트를 활용하면 몇 줄의 코드만으로도 직관적인 버튼 효과를 만들 수 있습니다. 실습 예제를 통해 바로 적용 방법을 확인하고 따라 해볼 수 있습니다.

기본 예제: CSS + JS로 클릭 시 색상 변경

<button id="colorBtn">클릭해서 색상 바꾸기</button>

<style>
  #colorBtn {
    padding: 12px 24px;
    font-size: 16px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
</style>

<script>
  const btn = document.getElementById('colorBtn');
  let isBlue = true;

  btn.addEventListener('click', () => {
    if (isBlue) {
      btn.style.backgroundColor = '#e74c3c'; // 빨간색
    } else {
      btn.style.backgroundColor = '#3498db'; // 파란색
    }
    isBlue = !isBlue;
  });
</script>
HTML

예제 실행

예제 설명

  • transition : 버튼 배경색이 서서히 변화는 효과. UX가 좋아집니다.
  • 변수(isBlue)를 사용해 클릭 상태를 쉽게 토글할 수 있습니다.

확장 예제: 여러 색상 랜덤 변경

<button id="randomBtn">랜덤 색상으로 바꾸기</button>

<script>
  const colors = ['#3498db', '#e74c3c', '#2ecc71', '#f1c40f', '#9b59b6'];
  const randBtn = document.getElementById('randomBtn');

  randBtn.addEventListener('click', () => {
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    randBtn.style.backgroundColor = randomColor;
  });
</script>
HTML

예제 실행

예제 설명

  • 배열에서 랜덤 색상을 선택하면 클릭할 때마다 다양한 효과 가능
  • JavaScript에서 colors에 색상 코드를 변수로 담아서 처리
  • transition : 서서히 배경이 변경되는 효과

HTML + CSS만으로도 클릭 상태 표현 가능

<input type="checkbox" id="toggleBtn" hidden>
<label for="toggleBtn" class="toggle-label">클릭해서 색상 바꾸기</label>

<style>
  .toggle-label {
    display: inline-block;
    padding: 12px 24px;
    background-color: #3498db;
    color: white;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  #toggleBtn:checked + .toggle-label {
    background-color: #e74c3c;
  }
</style>
HTML

예제 실행

예제 설명

  • JS 없이도 체크박스 + CSS :checked 활용
  • CSS 트릭으로 간단한 UI 효과를 만들고 싶은 독자에게 추천

마무리

  • 버튼 클릭 색상 변경은 CSS 트랜지션과 JS 클릭 이벤트를 활용하면 쉽게 구현 가능
  • 랜덤 색상, 토글 색상 등 다양한 확장도 가능
  • HTML/CSS만으로도 체크박스를 활용하면 JS 없이 구현 가능
  • 블로그 포스팅에서는 “코드 → 실행 → 결과 확인” 형태로 제공하면 독자가 바로 체험 가능

Summary in English

This tutorial demonstrates how to create buttons that smoothly change color on click using CSS and JavaScript. Explore toggle, random color, and CSS-only techniques to practice interactive UI effects and easily apply them to real web designs.

관련 포스팅들

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

위로 스크롤