Home  >  Article  >  Web Front-end  >  How Can I Style Radio Buttons to Look Like Buttons Using Only CSS?

How Can I Style Radio Buttons to Look Like Buttons Using Only CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-23 12:36:08364browse

How Can I Style Radio Buttons to Look Like Buttons Using Only CSS?

Replacing Radio Buttons with Button-Like Elements

Radio buttons are commonly used in forms for user selection. However, customizing their appearance to mimic regular buttons can enhance the user interface.

Using CSS to Transform Radio Buttons

You can achieve this transformation solely with CSS, eliminating the need for external frameworks. The updated HTML structure remains unchanged, preserving its functionality.

HTML Markup

The HTML for the donation form remains the same, consisting of:

  • A
      list for radio button options
    • items containing radio buttons and their labels

    CSS Styling

    The following CSS code will transform radio buttons into button-like elements:

    .donate-now {
      list-style-type: none;
      margin: 25px 0 0 0;
      padding: 0;
    }
    
    .donate-now li {
      float: left;
      margin: 0 5px 0 0;
      width: 100px;
      height: 40px;
      position: relative;
    }
    
    .donate-now label,
    .donate-now input {
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
    
    .donate-now input[type="radio"] {
      opacity: 0.01;
      z-index: 100;
    }
    
    .donate-now input[type="radio"]:checked+label,
    .Checked+label {
      background: yellow;
    }
    
    .donate-now label {
      padding: 5px;
      border: 1px solid #CCC;
      cursor: pointer;
      z-index: 90;
    }
    
    .donate-now label:hover {
      background: #DDD;
    }

    How It Works

    • It positions both the radio button and label elements absolutely within the
    • items.
    • The radio button's opacity is set to 0.01, making it visually hidden.
    • When a radio button is checked, its linked label is highlighted with a yellow background.
    • The hover effect on labels is maintained.

    The above is the detailed content of How Can I Style Radio Buttons to Look Like Buttons Using Only 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