Subpar Web Dev
Subpar Web Dev

Reputation: 3280

How can I overlay an image on an element without creating an image element?

So let's say I have an HTML structure like

<div class="outer">
    <div class="inner">
        <h1>Here's a headline</h1>
        <p>Here's some text</p>
    </div>
    <div class="inner">
        <p>Blah blah</p>
    </div>
</div>

and I want the gif https://www.wpfaster.org/wp-content/uploads/2013/06/loading-gif.gif to overlay the entire thing when the class loading is added to outer. Is there a way to do this with pseudo-elements? Problem with adding a background-image is that it's behind the inner elements.

Upvotes: 0

Views: 259

Answers (2)

Kenney
Kenney

Reputation: 9093

Here's one way to do it:

.loading .inner { visibility: hidden; }

.loading {
  background-image: url('https://www.wpfaster.org/wp-content/uploads/2013/06/loading-gif.gif');
  background-size: contain;
  background-repeat: no-repeat;  
}

.loading .inner { visibility: hidden; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
    <div class="inner">
        <h1>Here's a headline</h1>
        <p>Here's some text</p>
    </div>
    <div class="inner">
        <p>Blah blah</p>
    </div>
</div>
<button onclick="$('.outer').toggleClass('loading')">Toggle</button>

Upvotes: 2

hopkins-matt
hopkins-matt

Reputation: 2823

This should be pretty close to what you are looking for. Might need to tweak background color.

CSS:

.outer {
  position: relative;
}

.outer.loading:before {
  background: #fefefe url('https://www.wpfaster.org/wp-content/uploads/2013/06/loading-gif.gif') center no-repeat;
  background-size: contain;
  content: "";
  display: inline-block;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

Demo: https://jsfiddle.net/hopkins_matt/ac5jr5nq/

Upvotes: 2

Related Questions