How to stack elements vertically in CSS

Building a cool feature where you need elements stacked up on top of one another? Or maybe you're showing information in a table or graph that needs to be stacked vertically. Whatever your use case, we are going to show you my process of how we stack elements vertically in CSS using margin-bottom.

First, let's set up our code. Of course, we'll start out with our HTML. For this example, we are going to have a circle with three balls inside, and each ball is going to be evenly spaced apart. It's basically a three-dotted dice.

Test your color ideas at DarkColors.

<div class="circle">

<div class="ball-container">

<div class="ball">

<div class="ball">

<div class="ball">

</div>

</div>

At this point, you should have a blank page because we haven't added any styles yet. But now, let's see how we're going to stack elements vertically in CSS, using CSS.
First, we'll create our circle. We are creating a simple black blue circle, like this:

.circle{

width: 300px;

height: 300px;

border-radius: 50%;

background-color: blue;

}

Now, you'll want a way of centering the balls inside the circle container, so we'll use these properties to stack elements vertically in CSS:

align-items: center;

display: flex;

justify-content: center;

Now that we have everything set up, how will we stack our elements vertically in CSS? We like to use the margin property to stack everything up. Basically, elements in HTML are already default stacked up, and you would use flexbox to adjust that.
But, for this example, we want the three dots to be centered, and also stack up. So by adding that margin-bottom property, there will be an even space under each ball which will allow the balls to stack up and create a nice design.

.ball{

width: 30px;

height: 30px;

border-radius: 50%;

background-color: white;

margin-bottom: 20px;

}

Other ways to stack elements in CSS

display: flex;

flex-direction: column;

Regular flexbox, but elements are flexed, or stretched vertically.
Something to remember is that elements in HTML are on default, rendered vertically, so in our experience, you only really have to worry about spacing out the elements on the top and bottom when stacking elements vertically in CSS.
Hope this helped.

If you're looking for a way to quickly test and color ideas for your website without having to code or design, check out our free color tester: DarkColors

Test your color ideas at DarkColors.