ScanSkill
CSS Examples

How to Add Space Between Elements using CSS

In this example, we will learn how to add space between elements using CSS. We can add space using margin-top, margin-right, margin-bottom, and margin-left property top add space on the top, right, bottom, and left side of the element respectively or we can use the margin element as a shorthand for these properties.

Prerequisites

Example

HTML

    <div class="container">
        <div class="content-1">
            This is content 1
        </div>
        <div class="content-2">
            This is content 2
        </div>
        <div class="content-3">
            This is content 3
        </div>
    </div>
    <div class="container">
        <div class="content-4">
            This is content 4
        </div>
        <div class="main-content">
            This is main content
        </div>
        <div class="content-6">
            This is content 6
        </div>
    </div>
    <div class="container">
        <div class="content-7">
            This is content 7
        </div>
        <div class="content-8">
            This is content 8
        </div>
        <div class="content-9">
            This is content 9
        </div>
    </div>

CSS

        .container {
            display: flex;
            flex-direction: row;
        }

        .container>div {
            border: 1px solid black;
        }

        .main-content{
            margin-top: 10px;
            margin-right: 20px;
            margin-bottom: 5px;
            margin-left: 30px;
        }

Output

How to Add Space Between Elements using CSS

Here, we used margin-top to add space at the top of the element and margin-right, margin-bottom, and margin-left at the right, bottom, and left side of the element respectively. We can also use the shorthand property as margin: 10px 20px 5px 30px;

Conclusion

In this example, we will learn how to add space between elements using CSS. we used the margin-top, margin-right, margin-bottom, and margin-left to add space to the top, right, bottom, and left sides of the element. The margin property can also be used as a shorthand property for these properties.