HTML & CSS: How to create a progress bar with stacked divs

In web design, there are lots of cases where you will need to stack <div> elements on top of each other in order to achieve certain effects or layouts. One example of this is a progress bar, where you have a background color, a foreground color (to mark the progress), and maybe a label.

The trick to stacking divs is to make a container div with a position: relative; and give the stacked divs position: absolute;. The stacked divs can also benefit from having a z-index.

 

Step 1: Create the container div

HTML

<div class="container-div">
</div>

CSS

.container-div {
  width: 90%;
  height: 48px;
  align: center;
  background-color: #deedf4;
  border-radius: 10px;
  text-align: center;
  vertical-align: middle;
  position: relative;
}

Here is what it looks like so far on Codepen:

See the Pen CSS stacked divs – Step 1 by Chris Nielsen (@Chris_Nielsen) on CodePen.0

 

Notes:
This container contains the background color for the progress bar and stretches 100%. The trick is to give this container a position: relative;

 

Step 2: Create the first stacked div

Create a new div that will sit on top of the container div. This div will show the progress via a different background color. The percentage width indicates the percentage complete. This div should have position: absolute; and have a z-index which will elevate it above the background container. Position absolute in this case means absolute in relationship to the container div.

HTML

<div class="container-div">
 <div class="percent-bar"></div>
</div>

CSS

.percent-bar {
 width: 30%;
 height: 48px;
 background-color: #59A3C8;
 border-radius: 10px;
 position: absolute;
 z-index: 2;
}

See the Pen CSS stacked divs – Step 2 by Chris Nielsen (@Chris_Nielsen) on CodePen.0

 

Step 3: Create the second stacked div

Just like the previous step, create another div that will sit on top of the container div and make this one position: absolute also!

HTML

<div class="container-div">
 <div class="percent-bar"></div>
 
 <div class="status-bar-text">
 <h3>30%</h3>
 </div>
</div>

CSS

.status-bar-text {
  width: 100%;
  height: 48px;
  position: absolute;
}

h3 {
  text-align: right;
  margin: 0px;
  padding-top: 10px;
  padding-right: 12px;
}

And the final result looks like this:

See the Pen CSS stacked divs – Step 3 by Chris Nielsen (@Chris_Nielsen) on CodePen.0