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

In this tutorial, we will learn how to give vertical space between two text boxes in HTML and CSS. In HTML, a textbox is created using the input element. When you are creating a form, you may want to give some vertical space between two text boxes for the sake of good user interface and user experience.

There are multiple ways to give vertical space between two text boxes. The simplest way is to use a bunch of break tags, but it might mess up your form layout. So in this tutorial, we will follow a different approach and utilize margin-top property. We will also use flexbox to make sure both the input and label elements are perfectly aligned.

In the following example, we will have two text boxes and we will add some vertical spacing in 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 div element is just a wrapper for the rest of the 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 and both the input and label elements have been wrapped with a div.
  • The second div has an id name of #space which we will use in the CSS file to add vertical space between the both the div elements.
  • 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>Space between two text boxes </title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name">
    </div>
    <div id="space">
        <label for="email">Email:</label>
        <input type="email" name="email">
    </div>
</body>

</html>

CSS

  • We are selecting all the div elements and using the display property and setting the value to flex, justify-content property value to flex-start, and setting the width value to 250px. As a result, we will get perfectly aligned text boxes.
  • We are selecting the label and using the flex-grow property and setting the value to 1. The flex-grow property specifies how much an item will grow compared to other items inside a container.
  • Lastly, we are selecting the last div using the id #space and setting the margin-top value to 15px. As a result, the text boxes will have some vertical space between them.
div {
    display: flex;
    justify-content: flex-start;
    width: 250px;
}

label {
    flex-grow: 1;
}

#space {
    margin-top: 15px;
}