1

I'm trying to create a header that uses a webp image as background if the browser allows it, but when not I want the browser to load a png instead.

this is the HTML I have

<div class="no-webp">
    <section class="section-hero box-container">
        <div class="container">
            <div class="row">
                <div class="col-12 hero-bg">

                </div>
            </div>
        </div>
    </section>
</div>

<div class="webp">
    <section class="section-hero box-container">
        <div class="container">
            <div class="row">
                <div class="col-12 hero-bg">

                </div>
            </div>
        </div>
    </section>
</div>

and this is the CSS I have so far:

section.section-hero{
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 296px;
}

.webp section.section-hero {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.webp);
}

.no-webp section.section-hero {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png);
}

but I can't figure out how to link everything together, any idea?

3 Answers3

1

If php is an option I recommend using this:

if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false ) {
   // yeah, webp is supported!
}

If you need to do it via JS, then check this one out.

Carlos Pinto
  • 136
  • 7
0

You can check for the browser using the method explained here. From there, you could check for the browsers that have it or not and add the relevant class to the HTML element in question.

So you would have a different class for each background image. For example:

.webp-supported {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.webp);
}

.webp-not-supported {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png);
}
Pytth
  • 4,008
  • 24
  • 29
0

The way I'd do it is by using the <picture> tag in HTML. This will work in every browser, as browsers which do not support the picture tag will just display whatever source is specified in <img>. For example:

<picture>
  <source srcset="/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.webp" type="image/webp">
  <source srcset="/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png" type="image/png"> 
  <img src="/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png" alt="Hero Banner">
</picture>
Lewis Farnworth
  • 265
  • 2
  • 8