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, I’m going to show you my process of how I 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, I’m 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.

<div class="circle">
  <div class="ball-container">
      <div class="ball"></div>
      <div class="ball"></div>
      <div class="ball"></div>
  </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. I’m creating a simple black blue circle, like this: (I need to figure out how to embed my Codepen projects so I can visually show my process and you can actually see the code live. Stay tuned for that)

.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;

Product of the Day: Web Developer Portfolio Template. If you’re a web developer or designer looking for a professional template to get your next job, try this template out! With simple HTML, CSS, and JS, you can get your new theme up and running in no time. This new HTML template is ready to go. Here’s the link.

Now that we have everything set up, how will we stack our elements vertically in CSS? I 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 my 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.

By:

Posted in:


Leave a Reply

%d bloggers like this: