CSS: A guide to correctly setting an image URL for a checked checkbox

In my current situation, I have a list of checkboxes with corresponding images. When a checkbox is checked, I would like to add a black circle behind the image.

Here is an example of the current output:

https://i.sstatic.net/Pq4vP.png

This is what I expect the output to look like:

https://i.sstatic.net/lVBeV.png

Here is the code used to create the checkboxes:

<div
                key={item.id}
                className="chk-multiple-badge form-check form-check-inline"
              >
                <input
                  className="chkbox-badge form-check-input"
                  type="checkbox"
                  id={item.id}
                />
                <label
                  htmlFor={item.id}
                  className="form-check-label form-check-label-badge"
                >
                  <Row>
                    <Col>
                      <img
                        className="chk-badge-img"
                        src={item.imgBase64}
                        alt={item.badge_name}
                      />
                    </Col>
                  </Row>
                  <Row>
                    <Col>{item.badge_name}</Col>
                  </Row>
                </label>
              </div>

And here is the CSS for styling the checkboxes:

:checked + .form-check-label-badge:before {
  content: url("../../../../assets/images/checkd-badge.png");
  position: absolute;
  cursor: pointer;
}
.chkbox-badge {
  display: none;
}

Answer №1

Simple HTML/CSS Approach

Implementing this solution is straightforward.

Follow these steps:

Make sure each checkbox has a unique id attribute. This will allow you to associate a label with it using the for attribute of the label tag.

For instance:

<input type="checkbox" id="myCheckbox1" />
<label for="myCheckbox1"><img src="http://someurl" /></label>

Check out this functional code snippet :

ul {
  list-style-type: none;
}

li {
  display: inline-block;
}

input[type="checkbox"][id^="cb"] {
  display: none;
}

label {
  border: 4px solid transparent; border-radius: 50%;

  display: block;
  position: relative;
  margin: 10px;
  cursor: pointer;
}

label:before {
  background-color: white;
  color: white;
  content: " ";
  display: block;
  border-radius: 50%;
  border: 1px solid grey;
  position: absolute;
  top: -5px;
  left: -5px;
  width: 25px;
  height: 25px;
  text-align: center;
  line-height: 28px;
  transition-duration: 0.4s;
  transform: scale(0);
}

label img {
  height: 100px;
  width: 100px;
  transition-duration: 0.2s;
  transform-origin: 50% 50%;
}

:checked + label {
  border-color: #000;
}

:checked + label:before {
  content: "✓";
  background-color: grey;
  transform: scale(1);
}

:checked + label img {
  transform: scale(0.9);
border-radius: 50%;
  z-index: -1;
}
<ul>
      <li><input type="checkbox" id="cb1" />
        <label for="cb1"><img src="https://m.media-amazon.com/images/I/61Dnvcie7PL._SL1024_.jpg" /></label>
      </li>
      <li><input type="checkbox" id="cb2" />
        <label for="cb2"><img src="https://m.media-amazon.com/images/I/91vx4DQg4jS._AC_SX466_.jpg" /></label>
      </li>
      <li><input type="checkbox" id="cb3" />
        <label for="cb3"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSZ31Gis0FZirNYl6OGbnHlXWJTtgZXUVB6eNt7DomL5ZnK_v94cJpNLw24jKMcuQW3q7U&usqp=CAU" /></label>
      </li>
   
    </ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Your React.js app with Script Insertion Using HTML/JSX

I'm attempting to apply a style to an HTML element only when the property of an array of objects meets a certain condition, but I encountered this error: /src/App.js: Unexpected token, expected "..." (35:25) Here's my code: codesandbox export de ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

Navigating the website with curtain.js and anchor tags

Currently, I am working on a website located at www.TheOneCraft.co.uk. I have incorporated the curtain.js jQuery plugin to create animated slide/pages as users scroll down. However, I have been unsuccessful in making the navigation bar follow this animati ...

Can someone guide me on developing a similar design utilizing HTML canvas with HTML 5 technology?

Hey everyone, I could really use some assistance on creating a design with Html 5 canvas. My current issue is that the rectangles I'm trying to generate are overlapping and not fitting properly within the canvas. Below, you'll find both a referen ...

Hovering in Javascript

Imagine I have the following code snippet: <div class="class1"> ... random content </div> I want to use JavaScript so that when I hover over that div, a CSS attribute is added: background-color:#ffffe0; border:1px solid #bfbfbf; This is a ...

Ways to gradually reveal all elements within a header section

Is there a way to gradually reveal all the components in my header once the window has finished loading by utilizing jQuery's fadeIn function? Below is the pertinent code snippet: HTML <div class="banner"> <header class="header"> < ...

Could the addition of iframes enhance the efficiency of websites containing a vast amount of DOM elements?

When dealing with websites that have a massive amount of DOM elements, could there be any performance advantages to displaying some content within an iframe? For instance, the project I am currently involved in features a large HTML-based tree structure ...

What is causing Angular to consistently display the first object in the array on the child view, while the child .ts file correctly prints information from a different object?

Once a card of any object is clicked, the information of that specific object will be printed to the console. However, the child view will only display the details of the first object in the array it retrieves from. All pages are included below. A visual e ...

Creating a responsive grid division

.subcategory-main-wrapper { display: grid; grid-template-columns: repeat(4, max-content); position: absolute; width: 100%; column-gap: 4%; justify-content: center; height: 360px; @media @tabletScreens { height: 280px; } @media @ ...

Can text be replaced without using a selector?

I am utilizing a JavaScript library to change markdown into HTML code. If I insert <span id="printHello></span> within the markdown content, I can still access it using getElementById() after conversion. However, there is one scenario where th ...

What is the best way to stretch the background image across both the footer and navbar for my app?

Here is the code snippet I am currently working with: <template> <v-app> <AppBar></AppBar> <v-main> <router-view></router-view> </v-main> <Footer></Footer> ...

What is the best way to access and verify data from an array that has been passed through props

I am working with a component that takes an array as a prop <Component runners={['1','2']}/> Inside this functional component, my goal is to generate an element for each value in the array. Here's my logic: const { runners ...

Position tables on the right side of adjacent tables

There are two tables named id="BFCategories" and "BMICategories". Additionally, there are two other tables with id="BFTable" and "BMITable" BFCategories should come after BFTable, while BMICategories should follow BMITable. How can I a ...

Creating a scrolling sidebar in Bootstrap 4

Today I learned about CSS Bootstrap 4 and created my template with a sidebar. However, when there are many menus, I want the sidebar to show a scrollbar. I am looking for help on how to make a scrollbar appear on my sidebar template. Below are my HTML and ...

Incorporating React.js with a server API that doesn't use JavaScript

My upcoming project involves enhancing my current application frontend by implementing React.js. The existing frontend currently utilizes standard REST calls to communicate with a server built using Microsoft technologies, and there are no plans of changin ...

Various results can be produced based on the .load() and .resize() or .scroll() functions despite using the same calculation methods

I'm currently working on developing my own custom lightbox script, but I've hit a roadblock. For centering the wrapper div, I've utilized position: absolute and specified top / left positions by performing calculations... top: _center_ver ...

React Native Async Storage: displaying a blank page issue

I am facing an issue while attempting to save my data locally using AsyncStorage, specifically with the getData method. const storeData = async (value: string) => { //storing data to local storage of the device try { await AsyncStorage.setItem(& ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Risk Score Generating Form

As I work on a comprehensive form, there are 5 sections for users to mark if they qualify (using checkmarks). The form consists of approximately 50 questions in total. Each section carries different weights/points (e.g., Section 1 is worth 1 point each, ...

A useful tip for jQuery users: learn how to prevent the context menu from appearing when a text box is

Is there a way to prevent the context menu from appearing in jQuery when the text box is disabled? The right-click disable functionality works well in all browsers except for Firefox. Please note that the right-click disable functionality works when the t ...