Home  >  Article  >  Web Front-end  >  How to Align Labels and Input Fields Horizontally in Web Forms?

How to Align Labels and Input Fields Horizontally in Web Forms?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 09:14:02911browse

How to Align Labels and Input Fields Horizontally in Web Forms?

Aligning Label and Input Elements Horizontally

Enhancing the aesthetics of web forms requires an ability to position labels and input fields alongside each other. This guide illustrates how to achieve this horizontal alignment using CSS.

The Issue:

As highlighted in the initial post, there are two main challenges:

  • Ensuring the label and input element occupy the same line.
  • Expanding the input field's width to fill the remaining space, regardless of the label's length.

Solution 1: Inline-Block

Using display: inline-block for both label and input elements allows them to align horizontally while maintaining their individual sizes. However, this may not fulfill the requirement of filling the remaining width for the input field.

Improved Solution: float/overflow Magic

  • Create a container for both label and input element.
  • Float the label to the left to allow the input to occupy the remaining space.
  • Hide overflow on the label's container to prevent double-row behavior.
  • Set width: 100% for the input element.

**CSS:

label {
    float: left
}
span {
    display: block;
    overflow: hidden;
    padding: 0 4px 0 6px
}
input {
    width: 100%
}

Solution 2: table-cell

Another effective approach is to treat both elements as table cells.

  • Create a wrapper container and set its display property to table.
  • Designate label as display: table-cell with width: 1px and white-space: nowrap to prevent overflow.
  • Set input field as display: table-cell and width: 100%.

**CSS:

.container {
    display: table;
    width: 100%
}
label {
    display: table-cell;
    width: 1px;
    white-space: nowrap
}
span {
    display: table-cell;
    padding: 0 0 0 5px
}
input {
    width: 100%
}

The above is the detailed content of How to Align Labels and Input Fields Horizontally in Web Forms?. 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