Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 393
Jithin Scaria Avatar asked Mar 01 '19 15:03

Jithin Scaria


2 Answers

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
like image 178
Sam Herrmann Avatar answered Nov 14 '22 22:11

Sam Herrmann


I had to do an inline style for mine to work

<section id="hero" style="background-image: url(./assets/pic.jpg)">
like image 24
Andy Avatar answered Nov 14 '22 23:11

Andy