Ad

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 ?

Ad

Answer

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
Ad
source: stackoverflow.com
Ad