skip to Main Content

I am trying to get a hero image on a website. I would like the hero image to switch between a mobile and full image version, so I decided to go with background-image instead of
I can’t get the image to show up.

HTML

<section class="hero">
    <div class="">Random CTA</div>
    <div class="heroImage"></div>
</section>

CSS

.heroImage {     
background-image: url("/img/heroImageMobile.png") no-repeat center top;     
background-size: cover;     
height: 1200px;     
width: 800px; 
}

Eventually, this would be my media query, but I currently have it commented out

@media only screen and (min-width: 640px) {
    .heroImage {
    background-image: url("img/heroImageFull.png") no-repeat center top;
    }

I have Google this and followed the suggestions on other posts:

  • I have added height and width to match the image.
  • I have let VS Code fill in the path, so it looks correct. I tried img/filename, /img/filename, and ../img/filename
  • I tried with both PNG and JPG file

What am I missing?

2

Answers


  1. You’ll have to use the background property instead of background-image property which is more specific

    background-image property only take the url path as value, not all properties

    See this fiddle

    See these resources

    https://developer.mozilla.org/en-US/docs/Web/CSS/background-image
    https://developer.mozilla.org/en-US/docs/Web/CSS/background

    Login or Signup to reply.
  2. if you want a different image size for each screen size or different images, use the HTML picture tag. This is useful for the image to change at any given size.
    https://www.w3schools.com/tags/tag_picture.asp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search