Reputation: 146450
There're many ways to accomplish fix-width labels when the corresponding form control is in some other node:
<label for="foo">Text</label>
<input id="foo">
However, I've been struggling to find a sensible way to do it when form control is inside the label:
<label>Text <input></label>
My best attempts imply taking form controls out of page flow thus break with items that have a different height, e.g.:
label{
display: block;
position: relative;
margin: 1em;
padding: 1em;
width: 9em;
background-color: azure;
}
input, textarea{
position: absolute;
top: 1em;
left: 11em;
width: 15em;
}
textarea{
height: 8em;
}
<div>
<label>Short <textarea></textarea></label>
</div>
<div>
<label>This is a very long label text <input></label>
</div>
<div>
<label>Average sized <input></label>
</div>
Given this HTML markup, is there any other reasonably simple CSS-only technique that expands vertically as needed, both for label and control?
Upvotes: 2
Views: 1208
Reputation: 8206
you can use display: table
and display: table-cell
. its pretty much compatible with all browsers across the board
label{
display: table;
position: relative;
margin-top: 20px ;
padding: 10px;
width: 300px;
background-color: azure;
}
label > span {
width: 100px;
display: table-cell;
vertical-align: top;
}
label > input, textarea{
display: table-cell;
width: 100%;
}
textarea{
height: 100px;
}
<div>
<label><span>Short</span> <textarea></textarea></label>
</div>
<div>
<label><span>This is a very long label text</span> <input></label>
</div>
<div>
<label><span>Average sized </span><input></label>
</div>
Upvotes: 0
Reputation: 195992
Depends on how you actually want it to look.
Using flex comes to mind.
Here is a simple test:
label{
display: flex;
position: relative;
margin: 1em;
padding: 1em;
width:23em;
background-color: azure;
}
input, textarea{
font:inherit;
width: 15em;
margin-left:auto;
flex:none;
box-sizing:border-box;
}
textarea{
height: 8em;
}
<div>
<label>Short <textarea></textarea></label>
</div>
<div>
<label>This is a very long label text <input></label>
</div>
<div>
<label>Average sized <input></label>
</div>
Upvotes: 2