Home >Web Front-end >CSS Tutorial >How to Align Labels and Inputs Horizontally with Dynamic Width in CSS?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 22:40:03781browse

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>
  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>

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>
  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>

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!

Statement:
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