Background image not showing up

New Page

How To Fix CSS Background Image Not Working | HTML/CSS

Posted: December 3, 2020

Working with background images in CSS can be tricky. Because even if you set it in code, there are other factors that can prevent the background image from appearing on the page.

To help, here are four ways to fix your background image that isn’t working, using HTML and CSS:

1. Check that your CSS file is correctly linked in your HTML file.

In order for your CSS styles to load on your website, you need to add a <link> tag to your HTML file. This tag should be placed inside the <head></head> tags and should look like this:

<link rel=”stylesheet” href=”/style.css”>

How can you tell if your CSS file was loaded successfully or not?

One sign is that if you load your website and the background is white, all text looks like Times New Roman font and there are no colors or other styles.

You can also check your browser’s inspect tool by right-clicking anywhere on the page and selecting “Inspect Element” or pressing Ctrl-Shift-I. In the Inspector, if you see an error that says 404 CSS file not found, or The resource… was blocked due to a MIME type mismatch, this tells you that there was a problem when loading the CSS file.

Display Error: Resource was blocked due to mime type mismatch

If you see any of these errors and your website doesn’t look stylish, the first thing to check is the <link> tag. Make sure the href attribute loads the same filename as your actual CSS file and the path is correct.

The path should be relative to the location of your HTML file. If the CSS file is in the same directory as your HTML file, you can set href to style.css (or whatever your CSS file name is).

I usually put a slash / before the path, for example: href=”/style.css”. This will ensure that the path starts at the root of your website.

You may need this if you have pages in different subfolders that load the same <head> tag. For example, if you are using a CMS (content management system) template where there is shared code.

2. Make sure the image path is set correctly in the background image URL.

Once you’ve made sure your CSS file is linked correctly, also check that the image itself is set correctly. Again, you’ll want to open your code inspector in the browser to check.

How do I know if the background image is loading correctly or not?

If the background image doesn’t seem to load and you see a 404 error in the Image Inspector, that’s a good indicator that there’s something wrong with the image itself.

Error displaying CSS 404-ing file

If this happens, check that the name of the image file matches the actual file and that the path in the background-image:url() email points to the correct location.

The location of the image file should be relative to the location of the CSS file itself, not the root of your website. So, if your CSS file is in a subfolder, the path may need to be different than if the CSS file was at its root.

To help explain this, suppose you have a website file structure like this:

(project folder) |– index.html |– (css) |– style.css |– (img) |– cat-pic-1.jpg

This website contains the index.html file in the root of the project, a css folder which contains the style.css file and an img folder which contains the cat-pic-1.jpg image.

In your CSS styles, if you want to load cat-pic-1.jpg as a background image, the file path should:

  • Go up one level out of the css folder,
  • Navigate to the img folder,
  • Then load the image file itself.

The background-image property in the CSS file should look like this: background-image: url(‘../img/cat-pic-1.jpg’).

The ../ symbols mean that you will go up one level in the file structure.

You can do the same thing by setting: background-image: url(‘/img/cat-pic-1.jpg’).

This approach uses the forward slash (/) to start from the website root, then going into the img folder to load the image file.

So whether you navigate up through parent folders or start at the website root, don’t forget to utilize your code inspector to test and check if the image is loading or giving you a 404 error.

3. Explicitly set the element’s width and/or height.

If the image isn’t showing up, but you aren’t getting any 404 errors, go into the code inspector and check the element itself.

If there is no HTML content in the element, it might have zero width or height (or both!). This means that even though the background image is technically loaded correctly, the element itself is essentially invisible if it’s 0px in size.

The code inspector that displays the image has a height of 0 pixels

Check out the above example showing a website and the code inspector. If you hover over the .card__image element on the right pane, a label will appear over the element on the left pane, telling you that it has 354px width and 0px height.

That 0px height means the element won’t be visible.

To fix it, explicitly set the height of the .card__image element to height: 120px. If the element might have text content of varying length, you can set it to min-height: 120px instead, so it will be a minimum of 120px tall but can be taller if the text content needs more space.

Map displaying background image correctly now 4. Assurez-vous d’utiliser la syntaxe correcte dans les propriétés d’arrière-plan CSS.

Une dernière chose que vous pouvez vérifier est si vous utilisez la syntaxe correcte pour les propriétés CSS d’arrière-plan.

Here are some common values ​​you might use, along with possible values:

  • background color: #000000;
  • background image: url(“/landscape1.jpg”);
  • background position: center;
  • background repeat: no repeat;
  • bottom size: blanket;

You can also use the shorthand property background which allows you to combine all these different values ​​into a single style rule:

background: #000 center/cover url(“/img/landscape1.jpg”) without repetition;

If you use this shorthand property with a large number of values, make sure the syntax is correct. The order of the various background properties shouldn’t matter, but there is a tricky catch if you set background-size.

The background-size value can only be used if it immediately follows the background-position value, with a forward slash (/) between them. In our example, it is written like this: center/cover, where center is the position of the background and cover is the size of the background.

You can use the background-position value alone, but if you try to use only cover , the CSS rule will be invalid and  none  of the background properties will work.

If this happens, you will be able to see the invalid rule in the Code Inspector like this:

Error displaying invalid CSS rule

Did you enjoy this post?

Tweet me about it! 😀

Do you want to learn how to create a website?

I’m taking a course that will teach you how to build a real-world responsive website from scratch!

Learn more

How To Fix CSS Background Image Not Working | HTML/CSS

Posted: December 3, 2020

Working with background images in CSS can be tricky. Because even if you set it in code, there are other factors that can prevent the background image from appearing on the page.

To help, here are four ways to fix your background image that isn’t working, using HTML and CSS:

1. Check that your CSS file is correctly linked in your HTML file.

In order for your CSS styles to load on your website, you need to add a <link> tag in your HTML file. This tag should be located inside the <head></head> tags and should look like this:

<link rel=”stylesheet” href=”/style.css”>

How to know if your CSS file is loaded correctly or not?

One sign is if you load your website and the background is white, all the text looks like Times New Roman font, and there are no colors or other styles.

You can also check your browser’s inspector tool by right-clicking anywhere in the page and selecting “Inspect Element” or pressing Ctrl-Shift-I. In the inspector, if you see an error that says 404 not found for the CSS file, or The resource… was blocked due to MIME type mismatch, that tells you that there was a problem loading the CSS file.

Display Error: Resource was blocked due to mime type mismatch

If you see one of these errors and your website looks unstyled, the first thing to check is In the <link> tag. Make sure that the href attribute is loading the same filename as your actual CSS file, and that the path is correct.

The path needs to be relative to where your HTML file is. If the CSS file is in the same directory as your HTML file, you can set href to be style.css (or whatever your CSS filename is).

I usually put a forward slash / before the path, for example: href=”/style.css”. This will make sure that the path will start at your website root.

You may need this if you have pages in different subfolders that are all loading the same <head> code. For example, if you’re using a templated CMS (content management system) where there is shared code.

2. Make sure the image path is set correctly in the background-image url.

Once you have made sure that your CSS file is linked correctly, also check that the image itself is set correctly. Again, you will want to open your code inspector in the browser to check.

Comment savoir si l’image de fond est chargée correctement ou non ?

Si l’image d’arrière-plan ne semble pas se charger et que vous voyez une erreur 404 dans l’inspecteur de l’image, c’est un bon indicateur qu’il y a un problème avec l’image elle-même.

Error displaying CSS 404-ing file

Si cela se produit, vérifiez que le nom du fichier image correspond au fichier réel et que le chemin dans l’image d’arrière-plan : url() va au bon emplacement.

The location of the image file should be relative to the location of the CSS file itself, not the root of your website. So if your CSS file is in a subfolder, the path may need to be different than if the CSS file was in your root.

To help explain this, suppose you have a website file structure like this:

(project folder) |– index.html |– (css) |– style.css |– (img) |– cat-pic-1.jpg

This website contains the index.html file in the project root, a css folder that contains the style.css file, and an img folder that contains the image cat-pic-1.jpg.

In your CSS styles, if you want to load cat-pic-1.jpg as a background image, the file path needs to:

  • Go up one level out of the css folder,
  • Navigate into the img folder,
  • Then load the image file itself.

The background-image property in the CSS file should look like this: background-image: url(‘../img/cat-pic-1.jpg’).

The ../ symbols mean that you will go up one level in the file structure.

You can do the same thing by setting: background-image: url(‘/img/cat-pic-1.jpg’).

This approach uses the forward slash (/) to start from the website root, then going into the img folder to load the image file.

So whether you navigate up through parent folders or start at the website root, don’t forget to utilize your code inspector to test and check if the image is loading or giving you a 404 error.

3. Explicitly set the element’s width and/or height.

If the image isn’t showing up, but you aren’t getting any 404 errors, go into the code inspector and check the element itself.

If there is no HTML content in the element, it might have zero width or height (or both!). This means that even though the background image is technically loaded correctly, the element itself is essentially invisible if it’s 0px in size.

The code inspector that displays the image has a height of 0 pixels

Check out the above example showing a website and the code inspector. If you hover over the .card__image element on the right pane, a label will appear over the element on the left pane, telling you that it has 354px width and 0px height.

That 0px height means the element won’t be visible.

To fix it, explicitly set the height of the .card__image element to height: 120px. If the element might have text content of varying length, you can set it to min-height: 120px instead, so it will be a minimum of 120px tall but can be taller if the text content needs more space.

Map displaying background image correctly now 4. Make sure you are using correct syntax in CSS background properties.

One last thing you can check is if you are using the correct syntax for the background CSS properties.

Here are some common ones you might be using, along with possible values:

  • background-color: #000000;
  • background-image: url(“/landscape1.jpg”);
  • background-position: center;
  • background-repeat: no-repeat;
  • background-size: cover;

You can also use the shorthand background property that lets you combine all those different values ​​in one style rule:

background: #000 center/cover url(“/img/landscape1.jpg”) without repetition;

Si vous utilisez cette propriété abrégée avec un grand nombre de valeurs, assurez-vous que la syntaxe est correcte. L’ordre des différentes propriétés d’arrière-plan ne devrait pas avoir d’importance, mais il y a un piège délicat si vous définissez background-size.

La valeur background-size ne peut être utilisée que si elle suit immédiatement la valeur background-position, avec une barre oblique (/) entre elles. Dans notre exemple, il est écrit comme ceci : center/cover, où center est la position de l’arrière-plan et cover est la taille de l’arrière-plan.

Vous pouvez utiliser la valeur background-position par elle-même, mais si vous essayez d’utiliser uniquement cover par elle-même, la règle CSS sera invalide et  aucune  des propriétés background ne fonctionnera du tout.

If this happens, you will be able to see the invalid rule in the Code Inspector like this:

Error displaying invalid CSS rule

Did you enjoy this post?

Tweet me about it! 😀

Do you want to learn how to create a website?

I’m taking a course that will teach you how to build a real-world responsive website from scratch!

Learn more

html div background image not appearing

Ask

Asked 8 years, 8 months ago

Edited 9 months ago

Seen 102,000 times

This question shows research effort; it is useful and clear

17

This question shows no research effort; unclear or not helpful

Keep this question.

View activity on this post.

I’m working on a webpage (I’m a newbie of course) and the background image doesn’t appear in the div. I tried both background image and background and both won’t work…here is the code

If anyone can help that would be great!!

<!DOCTYPE html> <html> <head> <style type=”text/css”> body {background-color:gray;} </style> </head> <body> <div style=”background-image: url(‘/ximages/websiteheader1.png’);height:200px;width:1200px;”> </div> </body> </html>

  • html
  • CSS
  • background

To share

Share a link to this question

Copy link CC BY-SA 3.0

Follow

Follow this question to receive notifications

edited January 22, 2014 at 1:30

Avatar of Daniel Flippance

Daniel Flippance

7,525 4 4 gold badges 41 41 silver badges 55 55 bronze badges

askedJan 22, 2014 at 1:18 am

Avatar of Abdul Ahmad

Abdul Ahmad Abdul Ahmad

9 257 16 16 gold badges 56 56 silver badges 117 117 bronze badges

8

  • can you verify that you have the correct path to your image?

    – jmore009

    Jan 22, 2014 at 1:19 am

  • Yes, I checked more than three times

    –Abdul Ahmad

    Jan 22, 2014 at 1:20 am

  • 2

    @AbdulAhmad you should check a fourth time cause that’s your issue.

    – Roko C. Buljan

    Jan 22, 2014 at 1:21 am

  • yeah it definitely is, i just ran your script with a different link and the image showed up fine

    – jmore009

    Jan 22, 2014 at 1:21 am

  • 1

    ok it’s showing up, thank you guys

    –Abdul Ahmad

    Jan 22, 2014 at 1:28 am

 | Show 3 more comments

5 respuestas5

Ordenado por: Restablecer a predeterminado

Puntaje más alto (predeterminado) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)

This answer is useful

29

This answer is not useful

Save this answer.

Show activity on this post.

I recommend moving your css from the inline scope. Assuming that your .png file actually exists, try setting the background size and repeat tags.

<!DOCTYPE html> <html> <head> <style type=”text/css”> body {background-color:gray;} #mydiv { background-image: url(‘/ximages/websiteheader1.png’); background repeat: no repeat; background size: contains; height: 200px; width: 1200px; } </style> </head> <body> <div id=”mydiv”> </div> </body> </html>

If that doesn’t work, try checking the response codes in your browser’s developer tools and make sure the URL is correct.

I hope this helps you!

compare

Share a link to this answer

Copy link CC BY-SA 3.0

Follow

Follow this answer to receive notifications

answeredJan 22, 2014 at 1:38 am

dev7 user avatar

dev7 dev7

6 111 5 5 gold badges 29 29 silver badges 62 62 bronze badges

0

Add a comment | 

This answer is helpful

twenty one

This answer is not helpful

Save this response.

Show activity on this post.

A fast refresher about paths

Absolute paths

https://website.com/assets/image.jpg

//website.com/assets/image.jpg image loaded using http or https protocols

Relative paths

(For internal use if the image is on the same server)

image.jpg image in the same folder as the document calling the image!

./image.jpg Same as above, image in the same folder as the document calling the image!

/assets/image.jpg Similar to Absolute Paths, just omitting the protocol and domain name Go search my image starting from my root folder /, than into assets/

assets/image.jpg this time assets is in the same place as the document, so go into assets for the image

../assets/image.jpg À partir de l’endroit où se trouve le document, remontez d’ un dossier ../ et accédez aux ressources

../../image.jpg reculez de deux dossiers , voilà mon image !

../../assets/image.jpg go two folders back to ../../ and then go into assets

compare

Share a link to this answer

Copy link CC BY-SA 4.0

Follow

Follow this answer to receive notifications

modified on December 18, 2021 at 0:28

answeredJanuary 22, 2014 at 2:20 am

User avatar of Roko C. Buljan

Roko C. Buljan Roko C. Buljan

184k 37 37 gold badges 293 293 silver badges 299 299 bronze badges

0

Add a comment | 

This answer is helpful

1

This answer is not helpful

Save this response.

View activity on this post.

For me it was because i was using an angular element directive to set the background but i forgot to set “display” to “block”. Ugh! I spent forever troubleshooting this! Had it been an attribute directive i likely would not have encountered this.

Share

Share a link to this answer

Copy link CC BY-SA 3.0

Follow

Follow this answer to receive notifications

answered Jul 28, 2015 at 20:13

Post Impatica User Avatar

Post Impatica Post Impatica

13.6k 7 7 gold badges 62 62 silver badges 70 70 bronze badges

Add a comment  | 

This answer is useful

0

This answer is not useful

Save this answer.

Show activity on this post.

I had the same problem I corrected the relative path to start from the same folder as the page and it worked: url(./images/1.jpg) instead of url(/images/1.jpg) I read somewhere that it’s better to do so always. let me know if it works.

Share

Share a link to this answer

Copy link CC BY-SA 3.0

Follow

Follow this answer to receive notifications

answered Jul 11, 2015 at 20:21

user avatar of freddy

freddy freddy

1

Add a comment  | 

This answer is useful

0

This answer is not useful

Save this answer.

Show activity on this post.

actually, the same problem has gone with me. the solution is here for that problem. you have to change your path background-image: url(‘/ximages/websiteheader1.png’); TO background-image: url(‘ximages/websiteheader1.png’);

actually, remove the first / from the path of the image.

Share

Share a link to this answer

Copy link CC BY-SA 4.0

Follow

Follow this answer to receive notifications

edited Jul 19, 2019 at 18:19

Alex user avatar

Alex

1,062 10 10 silver badges 28 28 bronze badges

answered Jul 19, 2019 at 17:05

Neeraj saini user avatar

Neeraj saini Neeraj saini

1 1 1 bronze badge

Add a comment  | 

Your Answer

¡Gracias por contribuir con una respuesta a Stack Overflow!

  • Please be sure to answer the question. Please provide details and share your research!

But avoid…

  • Ask for help, clarification or reply to other answers.
  • Make opinion-based statements; Support them with references or personal experience.

To learn more, check out our tips for writing great answers.

saved draft

Draft rejected

Sign up or log in

Sign up with Google

Sign up using Facebook

Sign up using your email and password

Send

Post as guest

name

Email

Required, but never displayed

Post as guest

Yam

E-mail

Required, but never displayed

Post your answer Ignore

En cliquant sur “Poster votre réponse”, vous acceptez nos conditions d’utilisation, notre politique de confidentialité et notre politique en matière de cookies

Pas la réponse que vous cherchez? Parcourir d’autres questions étiquetées

  • html
  • CSS
  • antécédents

ou posez votre propre question.

  • Le blog à débordement
  • Une conversation avec Matt Hicks de Red Hat sur son parcours de développeur à PDG (Ep. 494)

  • Vous avez manqué notre conférence Flow State ? Retrouvez toutes les sessions.

  • Présenté dans Meta
  • Les signets ont été enregistrés

  • Améliorations de la boîte de réception : marquage des notifications comme lues/non lues et filtre…

  • Réviseur par-dessus bord ! Ou une demande d’amélioration du guide d’intégration pour les nouveaux…

  • Mise à jour collective : membres reconnus, articles et GitLab

  • Dois-je expliquer les réponses en code des autres ?

Leap

0

JQuery: change the background image if a radio button is checked

Related

2548

Make a div fill the height of the remaining screen space

2433

How can I make a div no bigger than its content?

2191

Vertically align text next to an image?

413

CSS Display resized and cropped image

2479

How do I give text or an image a transparent background using CSS?

925

Stretch and scale a CSS image in the background – with CSS only

2569

How to make a 100% height div of the browser window

1948

How to automatically resize an image to fit a ‘div’ container?

1695

How to vertically align an image inside a div

8520

Why does HTML think “chucknorris” is a color?

burning questions from the net

  • Do some Simpsons characters age over time?
  • (Mathematics) How do you ask teachers about their work when you only have a vague understanding of their field?
  • The computer can’t do anything that I can’t do with pencil and paper.
  • Is it reasonable for my teacher’s director to prohibit me from having private communications with my co-director?
  • Subsequences with distinct values
  • Make curved ends that form a circular base?
  • Publish a program with a BSD license but closed source?
  • Can we test security using Apex Tests & System.runAs()?
  • Zottffssentettffssen
  • Is TTGATATAT a gene?
  • How can I change the end of the line in tikz?
  • Two equations related to a sport
  • How do “dotted inseam = one beat” teachers handle “irregular compound” measurements (eg, 5/8)?
  • How to horizontally center an enumeration screen
  • What is the earliest example of published fiction showing an element of the future traveling through time alone?
  • Who introduced the notion of 2 categories?
  • How do compilers work in a language that doesn’t allow recursion?
  • Simple Figure Fonts
  • Can you unite a different spirit by re-founding Find Steed?
  • Could a society of pure sign language be as advanced as a society of speech?
  • How can a single knife attack deal 61 damage?
  • What do 1/4, 3/8 and 1/2 mean on impact drivers?
  • Should login attempts be denied when the correct password has recently been added to a denied password list?
  • Cannot create files or directories starting with ‘com1’ through ‘com9’

question flow

Subscribe to RSS

question flow

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.


Video Background image not showing up

Related Posts

Fatal error require failed opening required

Contents1 Fatal error of PHP No se pudo to open the archive requerido2 Subscribe to RSS3 About WPML3.1 From day one, our priorities have remained the same…

Your media file could not be processed.

Contents1 Fixed: Twitter Error “Your media file could not be processed”1.1 freno de mano1.2 ClipChamp Créer1.3 FilmoraGo1.4 adobe sparkle2 Video Your media file could not be processed….

Gravity forms not sending email

Contents1 [SOLVED] Why doesn’t Gravity Forms send email?1.1 How does Gravity Forms send email?1.2 Résoudre les problèmes liés aux formulaires Gravity qui n’envoient pas d’e-mail1.3 Configure Gravity…

This webpage is not founderr_file_not_found

Contents1 Install and manage extensions1.1 Install trusted extensions1.2 Agregar o eliminar el acceso a un sitio específico1.3 Hide extensions1.4 Show extensions2 5 Ways To Permanently Fix Chrome…

Continue to this website not recommended missing

Contents1 Ignore the “Continue to this website (not recommended)” message1.1 publication information1.2 Information1.3 Contents1.4 Admin Items2 Internet Explorer 10 ‘Continue to this website’ is missing option2.1 Similar…

Error loading stream id not found on server

Contents1 JWPlayer 6 error message “Error loading stream: ID not found on server”1.1 Inscrivez-vous ou connectez-vous1.2 Post as guest1.3 Post as guest2 Subscribe to RSS3 Problems with…