Antony Jones
Antony Jones

Reputation: 3190

How can I bring a div above the current front-most (z-index: 0) div?

I'm building a gauge which uses pure CSS. It has a background to clip the remainder of the progress colour from showing. I want to add another div on top which gives a text indication of the progress: "10%".

It seems like no matter what I do, I end up with the background clip covering my text.

I've got an example of the problem here:

https://svelte.technology/repl?version=1.60.3&gist=77e1b55c23e229dee8d45b5648610593

An extremely cut down version of my code, demonstrating the problem is as follows:

<div class="gauge-wrap">
    <div class="gauge-core">
        <div class="gauge-bg" style="background-color: #fff;">
            <div class="gauge-bg-value">10 %</div>
        </div>
        <div class="gauge-cap" style="background-color: #000;"></div>
    </div>
</div>

<script>
.gauge-bg-value {
  position: relative;
  color: #f0f;
  top: 7px;
  z-index: 6;
}

.gauge-wrap {
  position:relative;
  margin:0 0 20px;
}

.gauge-bg {
  position: absolute;
  width: 200px;
  height: 200px;
  border-radius:100px;
  z-index:0;
}

.gauge-cap {
  position: absolute;
  top:16px;
  left:16px;
  width: 168px;
  height: 168px;
  z-index:5;
}
</script>

It seems like z-index: 0 is still on top of my text div (.gauge-bg-value), even though I've given it a higher index.

Update - Solution:

In building my example, I moved the text into the .gauge-cap div and now it sits on top. Perhaps it was that div covering it all along. Happy to hear solutions that don't modify the structure of the html though.

Upvotes: 0

Views: 638

Answers (1)

Rich Harris
Rich Harris

Reputation: 29615

This is to do with stacking context. In a case like this...

<div class='foo'>
  <div class='bar'></div>
</div>

<div class='baz'></div>

...if foo and baz both create stacking contexts, and baz has a higher z-index than foo, then bar can never appear above baz no matter what. You'll have to break your markup apart into different layers instead (though in your example, I think you'd have an easier time using SVG instead of HTML).

Upvotes: 2

Related Questions