CSS How to get background-image from local disk or git?

39 Views Asked by At

I am trying to get a picture from my local disk to be a background for part of my page but I am not capable of actually linking it, even after searching for it for quite a looong time.

And also, how could I get it the same way from github, so it doesnt need to be stored on my local disk.

(its a random picture as I am just learning with it, same goes for the page itself)

In index.html I have:

 <div id="banner">
    <div class="content">
      <h1>RECIPES</h1>
    </div>
  </div>

In style.css:

  #banner {
    background-image: url(C:\Programming\Recipe\cooking\baking.jpg);
    background-size: cover;
    height: 300px;
    width: 100%;
  }
  
  #banner .content h1 {
    border: 3px solid white;
    position: relative;
    top: 50px;
    width: 400px;
    margin: 0 auto;

Ive tried options Ive found everywhere online, this one should be correct by another stack overflow solution but its not showing me anything.

This is a link for the same picture but on github https://github.com/dzu1i/cooking/blob/de881f3104b43d5bd4e9b297fa1af16df8ec461a/baking.jpg

As URL in html should then be used this (by copying image adress but that also doesnt work): https://github.com/dzu1i/cooking/blob/main/baking.jpg?raw=true

Could anybody help me, either solution is fine, I just want to figure out why its not working?

2

There are 2 best solutions below

0
André Abboud On

To fix this, move your image file (baking.jpg) into the same directory as your HTML file and add it in assets folder for example and then use a relative path like this:

#banner {
  background-image: url('assets/baking.jpg');
  background-size: cover;
  height: 300px;
  width: 100%;
}

0
CodeNinjaCaffeineJunkie On

I was able to get this to work by using a relative path. If the CSS file is in a child directory of your main program, you can start the relative path with two dots (..) to go up a directory.

For example,

Let’s say this is your project structure:

- main_program_directory
  - css
    - styles.css
  - images
    - background.jpg

The CSS would be:

body {
  background-image: url('../images/background.jpg');
  /* Other styles */
}