8

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 ?

Jithin Scaria
  • 1,271
  • 1
  • 15
  • 26

2 Answers2

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
Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50
  • Path relative to the base URL works fine.. Just like you said, CLI created a copy in into root directory , build renames the files to unique names as well, so it doesn't make any issue as well. but this issue is only when serves with `ng serve`. so either It should be mandatory to use path relate to base URL, or it works both with build and ng serve same way right ? isn't it odd ? – Jithin Scaria Mar 01 '19 at 19:17
  • has problem if using relative if there are duplicate asset file names (different content/image), they overwrite each other in the root, and not consistent which one wins. That's my experience. – Chau Nguyen Nov 19 '19 at 20:40
1

I had to do an inline style for mine to work

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