Relative path is not considered for background image configured in component css when ng serve Angular app

I have two div with id div1 and div2, I need to set two different background image for them, the images have the same name but located in different folders, so i configured as below,

app.component.html :

<div id="div1"></div>
<div id="div2"></div>

app.component.css:

background-image with different path for each div.

#div1 {
  background-image: url('../assets/images/videos/back.jpg');
  /* other styles */
}

#div2 {
  background-image: url('../assets/images/blogs/back.jpg');
   /* other styles */
}

Problem :

Both div shows the same background image while i serve the app using ng serve .

Please note that path to both images are different but the name is same

Reason :

When checked in developer tools of the browser, the style is coming as below,

#div1 [_ngcontent-c0] {
    background-image: url(back.jpg);
    /* other styles */
}

#div2 [_ngcontent-c0] {
        background-image: url(back.jpg);
        /* other styles */
}

that is Instead of url('../assets/images/blogs/back.jpg') it is coming as url(back.jpg) – with out the relative path, hence both showing the same image in background.

Question :

Is this an expected behavior for angular ? If not what am I missing here ?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Relative paths in CSS should be relative to the base URL, not relative to the component within the src directory. Therefore remove the leading .. from the path but make sure you have the leading slash:

#div1 {
  background-image: url('/assets/images/videos/back.jpg');
}

#div2 {
  background-image: url('/assets/images/blogs/back.jpg');
}

Based on experimentation, I can see that when using a path relative to the source code, the CLI creates a copy of the referenced image and drops it at the root of the dist folder. This causes the dist folder look as follows:

/dist
  // This is the image that the CLI created 
  // and your component is referencing, but 
  // you want to reference the images in the
  // assets folder.
  back.jpg
  /assets
      /images
          /videos
              back.jpg
          /blogs
              back.jpg

Solution 2

I had to do an inline style for mine to work

<section id="hero" style="background-image: url(./assets/pic.jpg)">

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply