November 27, 2022
How to Give Vertical Space Between Two Div Elements using HTML and CSS
In this tutorial, you will learn how to give vertical space between two div elements using HTML and CSS. The div tag is also known as a division tag, which is most frequently used in HTML to make divisions of content in the webpage. The div tag has both opening and closing tags.
There are multiple ways to add vertical space between two div elements. The simplest way is to use break tags, but in this tutorial, we will utilize the margin-top
property to give some vertical space between two div elements.
In the following example, we have two div elements and we will give some vertical space in between them. Please have a look over the code example and the steps given below.
HTML
- In the HTML file, we have 2
div
elements with some text content. - The first div has a class name of
.container-1
and the second div has a class name of.container-2
, which we will use in the CSS file to give different background colors to both div elements and to give some vertical space in between them. - 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>Vertical space between two divs</title> <link rel="stylesheet" href="./style.css"> </head> <body> <div class="container-1">container one</div> <div class="container-2">container two</div> </body> </html>
CSS
- We are selecting all the div elements using the element selector and setting the
height
property value to 200px,width
property value to 200px,color
property value to white,font-size
property value to 1.5rem, andtext-transform
property value to uppercase. As a result, we will have the same height and width divs with white-colored text. - We are selecting the first div using the class name
.container-1
and setting thebackground
property value to red to get a red color background div. - Lastly, we are selecting the second div using the class name
.container-2
and setting thebackground
property value to green andmargin-top
property value to 3rem. As a result, we will get a green color background div and have some vertical space between two div elements.
div { height: 200px; width: 200px; color: white; font-size: 1.5rem; text-transform: uppercase; } .container-1 { background: red; } .container-2 { background: green; margin-top: 3rem; }