CSS: Wrap div exactly around checkbox
Asked Answered
L

1

6

I would like to fit a div exactly around a checkbox. I am doing this because I want to use it to set a background color of the checkbox.

I've tried this, but the pink div sticks out below the checkbox.

jsFiddle

#checkbox{ margin:0px; 
           padding:0px;
           opacity:0.5;}

#checkbox_wrapper{ background:pink;
                  float:left;}

<div id = "checkbox_wrapper" >
      <input  type="checkbox" id = "checkbox"/>
</div>
Lysol answered 24/3, 2013 at 9:12 Comment(1)
Thanks to whoever made that jfiddle for me!Lysol
U
5

Set line-height to 0, the default font size was setting the height as 20px.

jsFiddle

enter image description here

#checkbox_wrapper {
    background:pink;
    float:left;
    line-height:0;
}

PS cool trick, I'm going to use it in the future ;)

Update

Here's another way to implementation, with no wrapper or class required. Unfortunately only works in IE9+, Chrome and Safari. Apparently it's against the CSS 2.1 spec.

jsFiddle

HTML

<input type="checkbox" />

CSS

input[type=checkbox] {
    position:relative;
}
input[type=checkbox]:before {
    content:"";
    display:block;
    background:pink;
    position:absolute;
    left:0;
    top:0;
    right:0;
    bottom:0;
    z-index:1;
    opacity:0.5;
}
Umbra answered 24/3, 2013 at 9:17 Comment(4)
Perfect, thanks :) (I'll accept the answer when it allows me too - you were too fast!!)Lysol
I can't see the effect in the no-wrapper jsFiddle in Firefox 19.0.2 and Opera 12.14. It works in Safari 6.0.3 and Chrome 26.0.1410.43.Brad
Updated, generated content on form elements is against CSS 2.1 apparently bugzilla.mozilla.org/show_bug.cgi?id=241985 good catch.Umbra
Yea, I'm aware of that one but it isn't anything to do with this question.Umbra

© 2022 - 2024 — McMap. All rights reserved.