Q: How do I center the checkbox vertically? In this particular case, why is there empty space between checkbox borders and the containing element at all given that margin and padding are 0 for all elements?
Screenshot:
JSFiddle: http://jsfiddle.net/TZMF5/2/
HTML:
<div class="category-item">
<span class="input-container">
<input type="checkbox"/>
</span>
</div>
CSS:
.category-item {
display: table;
border: 1px solid #cccccc;
margin: 0;
padding: 0;
}
.category-item .input-container {
display: table-cell;
margin: 0;
padding: 0;
text-align: center;
}
.category-item .input-container input {
margin: 0;
padding: 0;
vertical-align: middle;
}
There are similar questions on SO to this. Couldn't find an answer that would work for this case. Thx!
Checkbox elements, like other input elements are subject to vendor specific appearance
styling- you can override this by using appearance:none
or -webkit-appearance:none
etc..however this will then stop the checkbox from rendering at all.
As such, you have to 'live' with the default styling to some extent and implement a few overrides, for vertical alignment in the example you have given, you have to 'bump it up' by 1px, eg:
.category-item .input-container input {
margin:-1px 0 1px 0; /* <-- here */
padding: 0;
vertical-align: middle;
}
More on appearance
from MDN
The -moz-appearance [sic] CSS property is used in Gecko (Firefox) to display an element using a platform-native styling based on the operating system's theme.
A workaround is to 'replace' the checkbox element entirely, whilst still retaining its functionality- this can be done by adding a label
element then applying som nifty CSS, for example, the below:
HTML
<div class="category-item">
<div class="input-container">
<input class='checkbox' id='checkbox' type="checkbox" />
<label for='checkbox' class='checkbox'></label>
</div>
</div>
CSS
.category-item {
display: table;
border: 1px solid #cccccc;
margin: 0;
padding: 0;
height:30px;
}
.category-item .input-container {
display: table-cell;
margin: 0;
padding: 0;
text-align: center;
vertical-align: middle;
height:30px;
}
label.checkbox {
position:relative;
vertical-align: middle;
border:1px solid black;
height:10px;
width:10px;
margin:0;
padding:0;
margin:-2px 0 2px 0;
line-height:1em;
padding:0;
overflow:hidden;
display:inline-block;
}
input.checkbox {
appearance:none;
height:0;
width:0;
overflow:hidden;
display:none;
margin:0;
padding:0;
-webkit-appearance:none;
}
input.checkbox:checked +label.checkbox:before {
content:'\2713';
position:absolute;
top:-3px;
font-size:10px;
left:2px;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With