Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Tags:

html

css

forms

I would like to create an HTML form for user feedback. If the overall feedback is good, the user should click on a laughing smiley, if the overall feedback is bad, the user should choose a sad smiley.

I think this should be done using radio buttons, with the smileys instead of the radio buttons. Maybe I'm wrong though...

Do you know how I can achieve this?

Thanks!

like image 415
learning-html Avatar asked Oct 09 '10 15:10

learning-html


2 Answers

Let's keep them simple, shall we. First off, using pure HTML + CSS:

<div id="emotion">     <input type="radio" name="emotion" id="sad" />         <label for="sad"><img src="sad_image.png" alt="I'm sad" /></label>      <input type="radio" name="emotion" id="happy" />         <label for="happy"><img src="happy_image.png" alt="I'm happy" /></label> </div> 

This will degrade nicely if there's no JavaScript. Use id and for attributes to link up the label and radiobutton so that when the image is selected, the corresponding radiobutton will be filled. This is important because we'll need to hide the actual radiobutton using JavaScript. Now for some jQuery goodness. First off, creating the CSS we'll need:

.input_hidden {     position: absolute;     left: -9999px; }  .selected {     background-color: #ccc; }  #emotion label {     display: inline-block;     cursor: pointer; }  #emotion label img {     padding: 3px; } 

Now for the JavaScript:

$('#emotion input:radio').addClass('input_hidden'); $('#emotion label').click(function(){     $(this).addClass('selected').siblings().removeClass('selected'); }); 

The reason why we're not using display: none here is for accessibility reasons. See: http://www.jsfiddle.net/yijiang/Zgh24/1 for a live demo, with something more fancy.

like image 153
Yi Jiang Avatar answered Sep 21 '22 08:09

Yi Jiang


You can take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:

.class-selector input{     margin:0;padding:0;     -webkit-appearance:none;        -moz-appearance:none;             appearance:none; } 

And then using labels for images as the following demos:

JSFiddle Demo 1

From top to bottom: Unfocused, MasterCard Selected, Visa Selected, Mastercard hovered

JSFiddle Demo 2

Visa selected

Gist - How to use images for radio-buttons

like image 23
Richard Cotrina Avatar answered Sep 21 '22 08:09

Richard Cotrina