Home Web Front-end CSS Tutorial How to change the color of radio button using css (code attached)

How to change the color of radio button using css (code attached)

Oct 12, 2018 pm 04:58 PM
css css3

The content of this article is about the method of changing the color of the radio button using css (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Have you ever been asked by the salesperson, "Can you change the color of this radio button! Let it match the theme color!", and then you suffered from the fact that the native does not support changing the color, and finally you were forced to make a makeshift one by yourself. use. If we abandon input[type=radio] and develop a new one, we find that it is very cumbersome to simulate selected, unselected, unavailable and other states, and it is even more annoying when it involves radio button groups. In fact, we can use label, ::before, : checked and tabindex, and then adding a small amount of JavaScript script can simulate a richer style "native" radio button. Let’s try it together!

Understand the radio button box

Since our goal is to change the color of the radio button box and other appearance features and behaviors are consistent with the original radio button box, then we You must first understand the original appearance characteristics and behaviors of the radio button.
1.Appearance features
1.1.Normal style

margin: 3px 3px 0px 5px;
border: none 0;
padding: 0;
box-sizing: border-box;
display: inline-block;
line-height: normal;
position: static;
Copy after login

Note: We must ensure that the layout characteristics are consistent with the original appearance, otherwise there is a high chance that the replacement with a custom radio button will affect The overall layout eventually resulted in being forced to adjust the layout characteristics of other elements to achieve overall coordination, thereby expanding the scope of modification.

1.2. Styles that get focus

outline-offset: 0px;
outline: -webkit-focu-ring-color auto 5px;
Copy after login

Note: The style that gets focus here only takes effect through the Tab key on the keyboard. If you click with the mouse, although the radio button has gained focus, the above style will not work. will not take effect.

1.3. Set to disabled style

color: rgb(84, 84, 84);
Copy after login

2. Behavioral characteristics
The behavioral characteristics of the radio button are obviously selected or not, and the change event of the selected state, so we must Keep providing change events externally.
It is also worth noting that when the radio button gets focus through the Tab key on the keyboard, and then presses the Space key, the radio button will be selected.

With the above understanding, we can start coding!

Stop talking nonsense and code

How to change the color of radio button using css (code attached)

##In the above picture, the left side is the native radio button, and the right side On the side is our custom radio button. From top to bottom, the styles are

unselected, selected, focused and disabled.

CSS part

label.radio {
  /* 保证布局特性保持一致 */
  margin: 3px 3px 0px 5px;
  display: inline-block;
  box-sizing: border-box;

  width: 12px;
  height: 12px;
}

.radio__appearance{
  display: block; /* 设置为block则不受vertical-align影响,从而不会意外影响到.radio的linebox高度 */
  position: relative;
  box-shadow: 0 0 0 1px tomato; /* box-shadow不像border那样会影响盒子的框高 */
  border-radius: 50%;
  height: 90%;
  width: 90%;
  text-align: center;
}
label.radio [type=radio] + .radio__appearance::before{
  content: "";
  display: block;
  border-radius: 50%;
  width: 85%;
  height: 85%;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  transition: background .3s;
}
label.radio [type=radio]:checked + .radio__appearance::before{
  background: tomato;
}
label.radio [type=radio][disabled] + .radio__appearance{
  opacity: .5;
}
label.radio:focus{
  outline-offset: 0px;
  outline: #999 auto 5px;
}
/* 通过鼠标单击获得焦点时,outline效果不生效 */
label.radio.clicked{
  outline: none 0;
}
/* 自定义单选框的行为主要是基于原生单选框的,因此先将原生单选框隐藏 */
label.radio input {
  display: none;
}
Copy after login
HTML part

<!-- 未选中状态 -->
<label>
  <input>
  <i></i>
</label>

<br>

<!-- 选中状态 -->
<label>
  <input>
  <i></i>
</label>

<br>

<!-- disabled状态 -->
<label>
  <input>
  <i></i>
</label>
Copy after login
JavaScript part

var radios = document.querySelectorAll(".radio")
radios.forEach(radio => {
  // 模拟鼠标点击后:focus样式无效
  radio.addEventListener("mousedown", e => {
    var tar = e.currentTarget
    tar.classList.add("clicked")
    var fp = setInterval(function(){
      if (document.activeElement != tar){
        tar.classList.remove("clicked")
        clearInterval(fp)
      }
    }, 400)
  })
  // 模拟通过键盘获得焦点后,按`Space`键执行选中操作
  radio.addEventListener("keydown", e => {
    if (e.keyCode === 32){
      e.target.click()
    }
  })
})
Copy after login
There are three points to note in this implementation:

1. Pass label passes the mouse click event to the associated input[type=radio], so you can safely hide the radio button and make use of the radio button's own characteristics. However, due to the limitations of the label control itself, for example, it is not a focusable element by default, so keyboard key events cannot be transferred to the radio button. Even if the tabindex feature is added, handwritten JS is required to implement it;

2. When tabindex is greater than or equal to When 0, it means that the element can get focus. When it is 0, it means that the order of focus is arranged according to the location of the element. When it is greater than 0, it means that the smaller the element, the focus will be obtained first;

3. Since the display of the radio button is inline-block, so the radio button will affect the line box height. When the elements in the custom radio button are inline-block, if the vertical-align setting is slightly careless, the line box where the internal element is located will be raised, causing the height of the line box where the custom radio button is located to become larger. . Therefore, here we adopt the method of setting the display of internal elements to block, which directly disables vertical-align and improves controllability.

Achieved through opacity:0

Above we associate the input[type=radio] of display:none with label to simplify the custom order using input[type=radio] The implementation of the selection box, but still requires handwriting JS to implement the behavioral characteristics of pressing the Space key to select. Is there another way that can save trouble? We just want users not to see the native radio button, so can we just set it to opacity:0? !

CSS part

.radio {
  /* 保证布局特性保持一致 */
  margin: 3px 3px 0px 5px;
  display: inline-block;
  box-sizing: border-box;

  width: 13px;
  height: 13px;
}
/* 自定义单选框的行为主要是基于原生单选框的,因此先将原生单选框透明,且沾满整个父元素 */
.radio input {
  opacity: 0;
  position: absolute;
  z-index: 1; /* 必须覆盖在.radio__appearance上才能响应鼠标事件 */
  width: 100%;
  height: 100%;
}
.radio__container-box{
  position: relative;
  width: 100%;
  height: 100%;
}
.radio__appearance{
  display: block; /* 设置为block则不受vertical-align影响,从而不会意外影响到.radio的linebox高度 */
  position: relative;
  box-shadow: 0 0 0 1px tomato; /* box-shadow不像border那样会影响盒子的框高 */
  border-radius: 50%;
  height: 90%;
  width: 90%;
  text-align: center;
}
.radio [type=radio] + .radio__appearance::before{
  content: "";
  display: block;
  border-radius: 50%;
  width: 85%;
  height: 85%;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  transition: background .3s;
}
.radio [type=radio]:checked + .radio__appearance::before{
  background: tomato;
}
.radio [type=radio][disabled] + .radio__appearance{
  opacity: .5;
}
.radio:focus-within .radio__appearance{
  outline-offset: 0px;
  outline: #999 auto 5px;
}
/* 通过鼠标单击获得焦点时,outline效果不生效 */
.radio.clicked .radio_appearance{
  outline: none 0;
}
Copy after login
HTML part

<!-- 未选中状态 -->
<span>
  <span>
    <input>
    <i></i>
  </span>
</span>

<br>

<!-- 选中状态 -->
<span>
  <span>
    <input>
    <i></i>
  </span>
</span>

<br>

<!-- disabled状态 -->
<span>
  <span>
    <input>
    <i></i>
  </span>
</span>
Copy after login
JavaScript part

var radios = document.querySelectorAll(".radio")
radios.forEach(radio => {
  // 模拟鼠标点击后:focus样式无效
  radio.addEventListener("mousedown", e => {
    var tar = e.currentTarget
    tar.classList.add("clicked")
    var fp = setInterval(function(){
      if (!tar.contains(document.activeElement){
        tar.classList.remove("clicked")
        clearInterval(fp)
      }
    }, 400)
  })
})
Copy after login
Summary

We can slightly modify the check box That’s it, and then it can be slightly encapsulated through VUE, React and other frameworks to provide a simpler API, which will be more convenient to use.

The above is the detailed content of How to change the color of radio button using css (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

See all articles