How to Give Horizontal Space Between Two Text Boxes in HTML and CSS

In this tutorial, you will learn how to give horizontal space between two text boxes in HTML and CSS. An area on the screen where the user can input text is known as an HTML text box. In a form element, text boxes are most frequently used. For a nice user interface and user experience, you might wish to leave some horizontal space between two text boxes when constructing a form.

There are multiple ways to give horizontal space between two text boxes. But for the sake of simplicity, we will use the CSS margin-left property. We are using CSS flexbox to make sure the input and label components are both horizontally center-aligned.

In the following example, we have two 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 3 elements (div, input, and label).
  • The parent div element has a class name of .parent-container, which we will use in the CSS file to horizontally center 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 data.
  • Both the input and label elements have been wrapped with a div.
  • The second child div element has a class name of .horizontal-space, which we will use in the CSS file to add some horizontal space between the two 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 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 child div element using the class .horizontal-space 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;
}