Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4+ background css reference URL image path

I am forever plagued by trying to reference an image from across my application. The directory structure is:

src/app/assets/images/splashImage.png

In this trivial case, I'm trying to reference it from:

src/app/app.component.html

The first line of the html:

<div class="splashContainer">

The css file:

.splashContainer {
background: url("../../assets/images/splashImage.png") no-repeat center center fixed;

The build diagnostic says it can't find the file at --> the URL path from above.

My rule that obviously is wrong is to count up starting at the folder housing the html. app is 1 and src is 2, which gets me above the assets folder. Thus the two ../ parts.

What am I doing wrong?

Thanks in advance. Yogi

like image 396
Yogi Bear Avatar asked Jan 31 '18 12:01

Yogi Bear


People also ask

How do I reference an image URL in CSS?

Usage is simple — you insert the path to the image you want to include in your page inside the brackets of url() , for example: background-image: url('images/my-image. png'); Note about formatting: The quotes around the URL can be either single or double quotes, and they are optional.

How do you add a background image to a relative path in CSS?

Use the Relative Path /image/picture to Set the Background Image in CSS. We can use the /image/picture file path format to set the background image in CSS. In such a format, the image is located inside the image folder. The image folder is located at the root of the current web.

What is URL in background image?

The url() value allows you to provide a file path to any image, and it will show up as the background for that element. You can also set a data URI for the url() .


2 Answers

Try

background: url(assets/images/splashImage.png) no-repeat center center fixed;
like image 165
nithalqb Avatar answered Sep 29 '22 09:09

nithalqb


Do not use paths like ../dir or ../../dir since relative paths like this will most likely fail in the server after build. Since assets/ folder is declared by default in the angular.json file. I suggest you use inline css just for the image only. For instance:

<div class="bg-div" style="background-image: url(assets/images/imageX.png)"></div>

Then continue with the other css in your css file: i.e.

.bg-div: {
  background-size: cover;
  background-position: center center;
  height: 100%;
  position: relative;
}

This way it will work for both local builds during development and during deployment. You wont have to change the paths during build again.

This is if you have another external css file apart from the main angular's styles.css

like image 25
briancollins081 Avatar answered Sep 29 '22 08:09

briancollins081