Search code examples
csscss-positionz-index

Problems with z-index? Text not showing in front of elements with background-color


I'm trying to use CSS to make a simple "progress bar" type element. For some reason, the text in the .label element is not showing in front of the bar, despite z-index being set. How can I make the text visible?

#tech-entries {
  width: 200px;
padding: 5px;
}
.tech-entry {
  position: relative;
  padding-bottom: 2px;
}
.tech-entry .label {
  text-align: left;
  padding-left: 2px;
  z-index: 5;
  height: 15px;
}
.tech-entry .barbg,
.tech-entry .bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 15px;
}
.tech-entry .barbg {
  background-color: white !important;
  width: 100%;
}
.tech-entry .bar {
  background-color: green !important;
  z-index: 4;
}
<div id="tech-entries">
  <div class="tech-entry">
    <div class="label">test1</div>
    <div class="barbg"></div>
    <div class="bar" style="width: 99%;"></div>
  </div>
  <div class="tech-entry">
    <div class="label">test2</div>
    <div class="barbg"></div>
    <div class="bar" style="width: 65%;"></div>
  </div>
  <div class="tech-entry">
    <div class="label">test3</div>
    <div class="barbg"></div>
    <div class="bar" style="width: 88%;"></div>
  </div>
</div>


Solution

  • z-index only applies top positioned elements, so you want to position your bar class absolutely and the label relatively.

    #tech-entries {
      width: 200px;
    }
    
    .tech-entry {
      position: relative;
      padding-bottom: 2px;
    }
    
    .tech-entry .label {
      text-align: left;
      padding-left: 2px;
      z-index: 5;
      height: 15px;
      color: white !important;
      position: relative;
    }
    
    .tech-entry .barbg,
    .tech-entry .bar {
      position: absolute;
      left: 0;
      top: 0;
      height: 15px;
    }
    
    .tech-entry .barbg {
      background-color: gray !important;
      width: 100%;
    }
    
    .tech-entry .bar {
      background-color: green !important;
      z-index: 4;
      position: absolute;
    }
    <div id="tech-entries">
      <div class="tech-entry">
        <div class="label">test1</div>
        <div class="barbg"></div>
        <div class="bar" style="width: 99%;"></div>
      </div>
      <div class="tech-entry">
        <div class="label">test2</div>
        <div class="barbg"></div>
        <div class="bar" style="width: 65%;"></div>
      </div>
      <div class="tech-entry">
        <div class="label">test3</div>
        <div class="barbg"></div>
        <div class="bar" style="width: 88%;"></div>
      </div>
    </div>