How to Add Horizontal Space Between Multiple Text Boxes in HTML and CSS

In this tutorial, you will learn how to add horizontal space between multiple text boxes in HTML and CSS. The input element in HTML is used to create a textbox where the user can enter the text. Text boxes are most frequently used in form elements. You may want to leave some horizontal space between text boxes when building a form to ensure a great user interface and user experience.

To give some horizontal space between multiple textboxes, we can use the CSS margin-left property. To ensure that the input and label components are both horizontally aligned, we are utilizing CSS flexbox.

In the following example, we have multiple text boxes and we will add some horizontal spacing between them. Please have a look over the code example and the steps given below.

HTML

  • In the HTML file, we have multiple elements (div, input, and label).
  • The parent div element has a class name of .parent, which we will use in the CSS file to horizontally align the child elements.
  • The label element is used to specify a label for an input field. The value of for attribute is set to the name of the corresponding input field.
  • The input element specifies an input field where the user can enter the data and both the input and label elements have been wrapped with a div.
  • The second, third, and fourth child div has the same class name of .space-between which we will use in the CSS file to add horizontal space between the text boxes.
  • In the head element, we have added a stylesheet (style.css) using the link element.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Horizontal space between two text boxes</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <div class="parent-container">
        <div>
            <label for="firstname">First Name:</label>
            <input type="text" name="name">
        </div>

        <div class="horizontal-space">
            <label for="lastname">Last Name:</label>
            <input type="text" name="name">
        </div>
    </div>
</body>

</html>

CSS

  • We are selecting the parent div using the class name .parent and setting the display property value to flex and justify-content property value to center to horizontally center align the child elements.
  • We are selecting the second, third, and fourth child div element using the class name of .space-between and setting the margin-left value to 20px. As a result, the text boxes will have some horizontal space between them.
.parent-container {
    display: flex;
    justify-content: center;
}

.horizontal-space {
    margin-left: 20px;
}