8

Can we use images in CSS background in Google AMP?

<pre>

    <div style="background-image: url(assets/img/business1.jpg);></div>


</pre>
quotesBro
  • 6,030
  • 2
  • 31
  • 41
Rakib Uzzaman
  • 91
  • 1
  • 1
  • 2

3 Answers3

10

You can do like this :

CSS on head section

<style amp-custom>
    .img-background { background-image: url(assets/img/business1.jpg); }
</style>

HTML

<pre>
<div class="img-background"></div>
</pre>
Bachcha Singh
  • 3,850
  • 3
  • 24
  • 38
  • How to display background image for dynamic loop content. eg display posts – Tamil Selvan C Nov 09 '17 at 13:09
  • Yes, you can achieve. In loop you have to create unique class and css in head section for same class – Bachcha Singh Nov 09 '17 at 16:24
  • I am trying to use this method and I want the image to fill the width of the screen and then have the height be calculated so the aspect ratio is 16 x 9, as can be easily done with an amp-image. How do I get the div the right size? Should I use an amp-img, and then position my text on top using 'position:absolute'? – Jim S Jan 24 '19 at 23:38
2

AMP does not support inline styles (like your example), but you could add a background-image by implementing styles the proper way in a <style amp-custom> tag in the <head>.

Read more here: Supported CSS - AMP

Jon Uleis
  • 17,693
  • 2
  • 33
  • 42
0

You can also mimic the behavior of a background image by creating a container with position: relative that wraps the amp-img and the content and make the content position: absolute and have it cover the dimensions of the amp-img like so:

.wrapper {
  position: relative;
  width: '1200px';
  height: '700px';
}

.content {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
<div class="wrapper">
  <amp-img
    src="https://www.variety.org.au/sa/wp-content/uploads/2016/06/placeholder.png"
    width="1200px"
    height="700px"
    layout="responsive"></amp-img>
  <div class="content">
    <h1>My Content </h1>
  </div>
</div>
mtngoat
  • 11
  • 2