How to Align Labels and Inputs Horizontally with Dynamic Width in CSS?

Patricia Arquette
Release: 2024-11-02 22:40:03
Original
744 people have browsed it

How to Align Labels and Inputs Horizontally with Dynamic Width in CSS?

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

  1. HTML: Use a label and span element to wrap the input:
<code class="html"><label for="test">Label</label>
<span><input name="test" id="test" type="text" /></span></code>
Copy after login
  1. CSS: Employ the overflow: hidden property on the span:
<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>
Copy after login

Table-Cell Display Technique

  1. HTML: Enclose the label and input within a container div:
<code class="html"><div class="container">
    <label for="test">Label</label>
    <span><input name="test" id="test" type="text" /></span>
</div></code>
Copy after login
  1. CSS: Utilize table display and table-cell properties:
<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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template