My 2019 Approach to Building Forms:
After encountering fatigue from typing out ids for every label/input
pair in form building, I decided to change my approach. By nesting the input
directly within the label
, I found that functionality remains intact without the need for individual ids. Additionally, I utilized the flexibility of flexbox
to streamline the process.
HTML Structure:
<label>
Short label <input type="text" name="dummy1" />
</label>
<label>
Somewhat longer label <input type="text" name="dummy2" />
</label>
<label>
Very lengthy label for testing purposes <input type="text" name="dummy3" />
</label>
CSS Styling:
label {
display: flex;
flex-direction: row;
justify-content: flex-end;
text-align: right;
width: 400px;
line-height: 26px;
margin-bottom: 10px;
}
input {
height: 20px;
flex: 0 0 200px;
margin-left: 10px;
}
Check out the Fiddle DEMO here!
The Original Recommendation:
If you're looking for an alternative to using span
, consider utilizing label
, which is designed to be paired with inputs and offers additional functions like focusing the input when clicked.
Below is an example of how this can be implemented:
HTML Markup:
<label for="dummy1">Title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">
<label for="dummy2">Longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">
<label for="dummy3">Even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">
Related CSS Styles:
label {
width:180px;
clear:left;
text-align:right;
padding-right:10px;
}
input, label {
float:left;
}
View the jsfiddle DEMO here.