How to Create a CSS Toggle Button With an Icon

0
440

Creating a CSS toggle button with an icon is simple and effective for various interactive web features. Below is an example of a toggle button that changes its icon when toggled.

Example: Toggle Button with CSS and Icons

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Icon Toggle Button</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
      background-color: #f4f4f4;
    }

    .toggle-btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      border: none;
      border-radius: 50%;
      background-color: #007BFF;
      color: white;
      font-size: 24px;
      cursor: pointer;
      transition: background-color 0.3s, transform 0.2s;
    }

    .toggle-btn:active {
      transform: scale(0.95);
    }

    .toggle-btn.toggled {
      background-color: #28A745;
    }
  </style>
</head>
<body>
  <button id="toggleButton" class="toggle-btn">
    <span id="icon">☀️</span>
  </button>

  <script>
    const toggleButton = document.getElementById('toggleButton');
    const icon = document.getElementById('icon');

    toggleButton.addEventListener('click', () => {
      toggleButton.classList.toggle('toggled');
      icon.textContent = toggleButton.classList.contains('toggled') ? '🌙' : '☀️';
    });
  </script>
</body>
</html>

How it works:

  1. CSS Styling: The .toggle-btn class styles the button. The toggled class applies a different background color for the active state.
  2. Icons: Unicode icons (☀️ for sun and 🌙 for moon) change when the button is toggled.
  3. JavaScript: Adds an event listener to toggle the toggled class and swap the icon when clicked.

 

Search
Sellect from all Categories bellow ⇓
Read More
Java
Steps to Change Package Name in Android Studio Project
Changing the package name in an Android Studio...
By flowisetech 2025-02-24 19:09:26 0 353
Social Media
How to Make Money from Facebook – A Step-by-Step Guide
Facebook offers numerous ways to earn money,...
By flowisetech 2025-02-24 08:26:57 0 347
Digital Marketing
Essential Features Every Successful E-commerce Website Needs
1. User-Friendly Navigation Explanation: A...
By flowisetech 2025-04-01 08:27:49 0 347
JavaScript
What to do When working with the DOM
When working with the DOM (Document Object...
By flowisetech 2025-02-03 17:34:36 0 700
Entrepreneurship & Start-ups
Entrepreneurship & Business: A Comprehensive Guide
Here’s a detailed guide on...
By flowisetech 2025-03-08 09:25:00 0 579