What is the best way to modify the color of the btn-primary (label) for an unchecked radio button

Objective: I am aiming to change the background color to #FFFFFF when the radio button is not checked and to #9381FF when it is checked.

Current Result: Currently, both buttons display a background color of #9381FF.

I am aware that using !important is not the ideal approach, but as a beginner, I am struggling to comprehend other solutions outlined in this Stack Overflow post, so I am trying to tackle this approach for now.

How can I make the unchecked radio button have a white background?

Client code for radio buttons:

    <% layout('layouts/boilerplate') %>

    <div class="col-md-4 mb-3">
        <div class="btn-group" role="group" aria-label="Event Filter">
          <input type="radio" class="btn-check" name="eventFilter" id="upcomingEvents" value="upcoming" autocomplete="off" checked>
          <label class="btn btn-primary" for="upcomingEvents">Upcoming events</label>
          
          <input type="radio" class="btn-check" name="eventFilter" id="pastEvents" value="past" autocomplete="off">
          <label class="btn btn-primary" for="pastEvents">Past events</label>
        </div>
      </div>    

CSS code:

.btn-primary,
.btn-primary:active,
.btn-primary:visited,
.btn-primary:checked,
.btn-primary:focus {
    background-color: #9381FF !important;
    border-color: #9381FF !important;
    color: #e8f1f9 !important;
    border-radius: 2em;
}

.btn-primary:hover {
    background-color: #6f5cd9 !important;
    border-color: #6f5cd9 !important;
    color: #e8f1f9 !important;
    border-radius: 2em;
}

.btn-primary:not(:checked) {
    background-color: white; /* Change background to white when unchecked and hovered */
    border-color: #9381FF;
    color: #e8f1f9;
    border-radius: 2em;
}

Note: my layouts/boilerplate file calls my app.css file after including the Bootstrap CDN (see below):

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="51333e3e25222523302111647f637f62">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9aba6a6bdbabdbba8b989fce7fbe7fa">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7L+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
    crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debcb1b1aaadaaacbfaef3b7bdb1b0ad9eeff0e6f0ef">[email protected]</a>/font/bootstrap-icons.css">

<script src='https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.css' rel='stylesheet' />
<link rel="stylesheet" href="/stylesheets/app.css">

Answer №1

Your design style indicates that the label should follow directly after the input element. You can achieve this by using the + selector in CSS to target the label immediately following the input element within the same parent container. Here is a simple CSS styling solution:

input[type="radio"] + label{
  background-color: #ffffff;
  border-radius: 2em;
}
input[type="radio"]:checked + label{
  background-color: #9381FF;
}

The first selector sets the base styles for the label, while the second selector updates the background color when the input is checked. More information on the + selector can be found here. If you need to differentiate these inputs, consider adding a .btn-check class to your input and apply additional classes as needed.

Reasons why your current code may not be working properly

Your current code fails because you are targeting the label itself, which is never checked. Additionally, the use of the .btn-primary class selects the label unconditionally, rather than only when the radio input is checked. To resolve this, focus on selecting the input instead of the label.

Your third css block will not execute as intended since the label cannot be "checked." The hover effect specified in your code will still work even if the input is not checked. When defining styles, prioritize updating only what needs to change to minimize redundancy.

Concluding thoughts

Avoid redundant declarations by setting baseline styles and modifying specific properties that require changes. Keep in mind the relationship between input and label elements for accurate styling implementation.

Answer №2

I don't have experience with working on bootstrap CSS, so I may not be able to provide detailed guidance on that specific topic. However, I can offer an alternative approach to achieving your desired outcome without directly modifying the .btn-primary styling.

If you only want to change the style of a single button, you can follow a similar method to the code snippet provided below. Simply remove the .btn-primary class and replace it with your custom class.

<div class="btn-group" role="group" aria-label="Event Filter">
      <input type="radio" class="btn-check radio" name="eventFilter" id="upcomingEvents" value="upcoming" autocomplete="off" checked>
      <label class="btn check" for="upcomingEvents">Upcoming events</label>
      
      <input type="radio" class="btn-check radio" name="eventFilter" id="pastEvents" value="past" autocomplete="off">
      <label class="btn check" for="pastEvents">Past events</label>
    </div>

.radio{
  display:none;
}
.check{
  border:none;
  outline:none;
  pointer-events:none;
}
.check{
  background:red;
  display:block;
  width:100px;
  height:100px;
}
.radio:checked ~ .check {
  background:black;
}

You can also refer to this CodePen link for further insights.

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

Struggling to create a web application using parcel-bundler (Java not loading post-compilation)

Hey everyone, I've been searching online for a solution to my problem with parcel while working on a bootstrap web project, but I haven't had any luck. So now, I'm reaching out to you all for help. Bear with me as I explain the situation in ...

Issue with the position of the search dropdown in HTML

When we click on the Dropdown option, it appears above the text instead of below. I have been trying to fix the positioning issue where the Dropdown shows up separately after clicking, but I have not been successful so far. Maybe you can offer some assist ...

Custom Jquery function is failing to position divs correctly within ajax-loaded content

I recently coded a custom function that efficiently positions absolute divs within a container by calculating top positions and heights: $.fn.gridB = function() { var o = $(this); //UPDATED from var o = $(this[0]); o.each(function() { var ...

Tips for resolving the issue encountered with a modal in bootstrap 5

Currently utilizing react 6 along with bootstrap 5. The issue seems to be related to the Modal component rather than the window, as indicated in the tutorial. The error message I'm encountering is: Warning: Can't perform a React state update o ...

What is the best way to incorporate dynamic elements into a canvas that evolve over time?

Whenever a user interacts with my website by clicking on various parts, I want to display an expanding circle. My idea is to achieve this using a canvas element. Currently, I have successfully implemented the feature where a circle is drawn at the position ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Using various HTML elements within Phonegap applications

Is it possible to include multiple HTML files in a Phonegap application? ...

JavaScript - Separate Artist and Title

In the code snippet below, I am using a Parser script to extract metadata from a live streaming radio station: const Parser = require('../src'); const radioStation = new Parser('http://stream.com/live_32.aac'); radioStation.on(' ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Angular in conjunction with socket.io does not immediately show messages on screen

I am currently working on developing an instant messaging app (chat) using socket.io and Angular. I have two main files: index.html and index.js as shown below. The chat functionality is working well, but I am facing an issue where the messages do not appe ...

I'm struggling to figure out how to specify the data type for storing an array of objects in a variable using React.useState

I am currently working on extracting values from an .xlsx file using the SheetJS library. Below, I will provide the code snippets, errors encountered, and the different approaches I have attempted. Data extracted from var dataToJson: (6) [{…}, {…}, { ...

Display the GIF when the mouse hovers over it, but ensure it plays just a single time

Is it possible to make a GIF only play once when you hover over it on a website? I want to avoid the animation repeating if the user hovers over it again without refreshing the page. Currently, I have a static image that changes to a gif on mouseover, but ...

ensure that the element matches the height of its parent element

Allow me to illustrate the issue with a visual aid. In the provided image, you can observe that the checkmark is perfectly centered vertically in the one-line p element. However, as the text extends to two or three lines within the p element, the checkmar ...

How to perfectly position an image within a fixed full screen container

When you click on a thumbnail image, a full-screen overlay with a larger version of the image will be triggered using JavaScript. To ensure that the image is centered and resized inside the black overlay when the browser window size changes, I attempted t ...

Tips for aligning the dropdown menu to start from the border of the menu bar instead of displaying directly below the text

I have designed a menu-header section for my website, inspired by this image. I created a fiddle to showcase it. However, I am facing an issue where the dropdown elements for "PROGRAMS" and "WORLD OF NORTHMAN" should start from the border of the header ins ...

I am facing a challenge with my data, as it includes start and end values representing character indexes for styles. I need to find a way to convert this information into valid HTML tags

I have some content from another source that I must transform into proper HTML. The content contains a string such as: "Hello, how are you?" Additionally, there is a separate section detailing styling instructions. For example: 'bold:star ...

The toggle for hiding and showing, along with changing the button color, is not functioning properly due to

I'm encountering a puzzling issue with a toggle that hides and displays information and changes color on click. The functionality works flawlessly on the page where I initially wrote the code. For instance, the button's background shifts colors w ...

"Encountered a Http502 error while running the Node component (code provided for reference purposes

Encountering the Http502 error while developing a node component for chatbot. The first code snippet works flawlessly, but the second one triggers an Http502 error. Both snippets share the same host and proxy settings, with only the endpoint being differen ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...

Transferring a variable between a JavaScript function and a Java class

Currently, I am working with STS and building an application that includes HTML files and JavaScript. Within this file, there is a function that configures variables. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www ...