Align Label and Input Horizontally with Dynamic Width
In web design, it's often necessary to position labels and their corresponding input elements on the same line. However, ensuring that the input element fills the remaining width regardless of the label's text can prove challenging.
To achieve this using CSS, consider the following techniques:
Overflow Hiding Technique
<code class="html"><label for="test">Label</label> <span><input name="test" id="test" type="text" /></span></code>
<code class="css">label { float: left; /* Align label to the left */ } span { display: block; overflow: hidden; /* Key trick for adjusting input width */ padding: 0 4px 0 6px; /* Add padding for visual consistency */ } input { width: 100%; }</code>
Table-Cell Display Technique
<code class="html"><div class="container"> <label for="test">Label</label> <span><input name="test" id="test" type="text" /></span> </div></code>
<code class="css">.container { display: table; width: 100%; } label { display: table-cell; width: 1px; /* Minimal width to accommodate label */ white-space: nowrap; } span { display: table-cell; padding: 0 0 0 5px; } input { width: 100%; }</code>
These techniques effectively align the label and input horizontally while ensuring the input element fills the remaining width, adapting to the length of the label text.
The above is the detailed content of How to Align Labels and Inputs Horizontally with Dynamic Width in CSS?. For more information, please follow other related articles on the PHP Chinese website!