ob. ob. - 5 months ago 31
CSS Question

Need html checkbox label to wrap "nicely"

I have a grid of checkboxes where each cell has a fixed width, and each checkbox is preceded with a small image. In cases where the label text is too long, I'm having a hard time getting the text to wrap underneath the checkbox.

screenshot 1

Referring to the above screenshot, I'd like "text that wraps" to be aligned with the checkbox, rather than wrapping underneath the image, like so:

screenshot 2

I've set up a fiddle with my current markup and styles. What I can't change is the HTML structure, but any CSS changes are fine.

Here is a code snippet:



.checkbox-list {
}
img.placeholder{
width:16px;
height:16px;
background-color:lightblue;
}
td {
padding:2px;
width:150px;
vertical-align:top;
}
label {
/*display:inline-block;*/
}

<table class="checkbox-list">
<tbody><tr>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Some really long text that wraps</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
</tr><tr>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
</tr>
</tbody></table>




Answer

You could just apply a margin-bottom to the image and float: left:

img.placeholder{
    width:16px;
    height:16px;
    background-color:lightblue;
    margin-bottom: 1em;
    float: left;
}

JS Fiddle demo.


Edited because I am, apparently, an idiot, and didn't realise the simplest approach was to assign the display: block; and margin-left: 18px; to the label element, and float the .placeholder elements:

img.placeholder{
    width:16px;
    height:16px;
    background-color:lightblue;
    float: left;
}

label {
    display: block;
    margin-left: 18px;
}

JS Fiddle demo.

Floating the image prevents the label from starting on a new-line, the margin-left on the label is the width of the image and a small 2px 'gutter' to visually separate the image and the checkbox (adjust to taste, obviously).

Comments