Nowadays, building custom checkboxes, radio buttons, and toggle switches is perfectly feasible, while maintaining semantics and accessibility. We don't even need a line of JavaScript code or extra HTML elements! Actually, it's easier lately than in the past. let's see.
The final effect is as follows:
Things are much easier than before!
The reason is that we can finally<input>
::before
and ::after
pseudo-elements of the tag itself are styled. This means we can keep and set<input>
style without any extra elements. Previously, we had to rely on extra<div> or<code><span></span>
to implement custom design.
Let's take a look at the HTML code
There is nothing special here. We just need to use this HTML code to style the input:
<input type="checkbox" id="c1"> <input type="radio" id="r1"> <input type="checkbox" id="s1">
This is all about the HTML part. Of course, it is recommended to add name
and id
attributes, as well as matching ones<label></label>
element:
<label for="c1">Check box</label> <input type="checkbox" id="c1"> <label for="r1">Radio button</label> <input type="radio" id="r1"> <label for="s1">switch</label> <input type="checkbox" id="s1" class="switch">
Start setting styles
First, we check support for appearance: none;
including its prefix version. appearance
attribute is key because it is designed to remove the browser's default style from the element. If the browser does not support this property, the style will not apply and the default input style will be displayed. This is absolutely fine and is also a good example of gradual enhancement.
@supports(-webkit-appearance: none) or (-moz-appearance: none) { input[type='checkbox'], input[type='radio'] { -webkit-appearance: none; -moz-appearance: none; } }
For now, appearance
is still in the working draft phase, but here is the support:
This browser supports data from Caniuse, which contains more details. The number indicates that the browser supports this feature in this and later versions.
Desktop
Mobile/tablet
Like links, we have to consider the different interaction states of form elements. We consider these states when setting element styles:
-
:checked
-
:hover
-
:focus
-
:disabled
For example, here is how to style our toggle input, create knobs, and consider :checked
status:
/* Switch container*/ .switch { width: 38px; border-radius: 11px; } /* Switch knob*/ .switch::after { left: 2px; top: 2px; border-radius: 50%; width: 15px; height: 15px; background: var(--ab, var(--border)); transform: translateX(var(--x, 0)); } /* Change color and position when selected*/ .switch:checked { --ab: var(--active-inner); --x: 17px; } /* Reduce the opacity of the toggle knob when the input is disabled*/ .switch:disabled:not(:checked)::after { opacity: .6; }
we will<input>
Elements are used as containers. The knob inside the input is created with the ::after
pseudo-element. Again, no additional marking is needed!
If you open the style in the demo, you'll see that we're defining some CSS custom properties, as this has become a great way to manage reusable values ??in the stylesheet:
@supports(-webkit-appearance: none) or (-moz-appearance: none) { input[type='checkbox'], input[type='radio'] { --active: #275EFE; --active-inner: #fff; --focus: 2px rgba(39, 94, 254, .25); --border: #BBC1E1; --border-hover: #275EFE; --background: #fff; --disabled: #F6F8FF; --disabled-inner: #E1E6F9; } }
But there is another reason we use custom properties - they are very suitable for updating values ??based on the state of an element! We won't go into details here, but the following is an example of how to use custom properties based on different states.
/* default value*/ input[type='checkbox'], input[type='radio'] { --active: #275EFE; --border: #BBC1E1; border: 1px solid var(--bc, var(--border)); } /* Rewrite the default value*/ input[type='checkbox']:checked, input[type='radio']:checked { --b: var(--active); --bc: var(--active); } /* If not selected and not disabled, another border color is applied when hovering*/ input[type='checkbox']:not(:checked):not(:disabled):hover, input[type='radio']:not(:checked):not(:disabled):hover { --bc: var(--border-hover); }
For accessibility we should add custom focus styles. We removed the default outline because it cannot be rounded like the rest of the style we set. However, box-shadow
with rounded corners can create a rounded corner style that works like an outline.
input[type='checkbox'], input[type='radio'] { --focus: 2px rgba(39, 94, 254, .25); outline: none; transition: box-shadow .2s; } input[type='checkbox']:focus, input[type='radio']:focus { box-shadow: 0 0 0 var(--focus); }
You can also align and set directly to follow in HTML<input>
Elemental<label></label>
Element style:
<label for="c1">Check box</label> <input type="checkbox" id="c1">
input[type='checkbox'] label, input[type='radio'] label { display: inline-block; vertical-align: top; /* Other styles*/ } input[type='checkbox']:disabled label, input[type='radio']:disabled label { cursor: not-allowed; }
Show the demo again:
Hopefully you can see how convenient it is to create custom form styles these days. It requires fewer markups due to pseudo-elements directly on form input. It requires fewer style switches due to custom properties. And thanks to @supports
it has pretty good browser support.
All in all, this is much better than the development experience we had to deal with in the past!
The above is the detailed content of Custom Styling Form Inputs With Modern CSS Features. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

TocreatestickyheadersandfooterswithCSS,useposition:stickyforheaderswithtopvalueandz-index,ensuringparentcontainersdon’trestrictit.1.Forstickyheaders:setposition:sticky,top:0,z-index,andbackgroundcolor.2.Forstickyfooters,betteruseposition:fixedwithbot

The scope of CSS custom properties depends on the context of their declaration, global variables are usually defined in :root, while local variables are defined within a specific selector for componentization and isolation of styles. For example, variables defined in the .card class are only available for elements that match the class and their children. Best practices include: 1. Use: root to define global variables such as topic color; 2. Define local variables inside the component to implement encapsulation; 3. Avoid repeatedly declaring the same variable; 4. Pay attention to the coverage problems that may be caused by selector specificity. Additionally, CSS variables are case sensitive and should be defined before use to avoid errors. If the variable is undefined or the reference fails, the fallback value or default value initial will be used. Debug can be done through the browser developer

ThefrunitinCSSGriddistributesavailablespaceproportionally.1.Itworksbydividingspacebasedonthesumoffrvalues,e.g.,1fr2frgivesone-thirdandtwo-thirds.2.Itenablesflexiblelayouts,avoidsmanualcalculations,andsupportsresponsivedesign.3.Commonusesincludeequal-

Mobile-firstCSSdesignrequiressettingtheviewportmetatag,usingrelativeunits,stylingfromsmallscreensup,optimizingtypographyandtouchtargets.First,addtocontrolscaling.Second,use%,em,orreminsteadofpixelsforflexiblelayouts.Third,writebasestylesformobile,the

Yes, you can use Flexbox in CSSGrid items. The specific approach is to first divide the page structure with Grid and set the subcontainer into a Grid cell as a Flex container to achieve more fine alignment and arrangement; for example, nest a div with display:flex style in HTML; the benefits of doing this include hierarchical layout, easier responsive design, and more friendly component development; it is necessary to note that the display attribute only affects direct child elements, avoids excessive nesting, and considers the compatibility issues of old browsers.
