Home >Web Front-end >CSS Tutorial >How to Replace Default Checkbox Images with Custom On/Off Images Using Pure CSS?

How to Replace Default Checkbox Images with Custom On/Off Images Using Pure CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 22:30:25958browse

How to Replace Default Checkbox Images with Custom On/Off Images Using Pure CSS?

Pure CSS Checkbox Image Replacement

For your checkbox list, you aim to replace the default checkbox images with custom on/off images using CSS.

To achieve this, follow these steps:

  1. Hide the Original Checkbox:

    • Use the CSS display: none; property to hide the native checkbox.
  2. Create a Custom Label:

    • Position a label adjacent to the hidden checkbox using label input.
    • This label will be responsible for displaying your custom images.
  3. Style the Label with Background Images:

    • Use background-image and the input[type=checkbox]:checked pseudo-class to toggle between the on and off images.
  4. Position the Images Correctly:

    • Adjust the background-position property to align the images correctly within the label.

Complete CSS Code Example:

input[type=checkbox] {
  display: none; /* Hide the checkbox */
}

input[type=checkbox] + label {
  display: inline-block; /* Position the label next to the checkbox */
  width: 16px; /* Width of the label = Width of the checkboxes */
  height: 16px; /* Height of the label = Height of the checkboxes */
  background-image: url('/images/off.png'); /* Default to "off" image */
  background-position: 0 0;
}

input[type=checkbox]:checked + label {
  background-image: url('/images/on.png'); /* Change image to "on" image when checked */
}

Note: Ensure that the paths to your custom images are correct. Refer to the provided JavaScript Fiddle and Gist for a complete working example.

The above is the detailed content of How to Replace Default Checkbox Images with Custom On/Off Images Using Pure CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Recipe Book Web InterfaceNext article:Recipe Book Web Interface