Angular 5 background image will not show
Asked Answered
V

3

9

I need help. I'm a complete beginner and I can't find solution anywhere, so sorry if it was already asked, but no matter what I tried I couldn't display background image on one page.

What I want to do?

Display the background image on home page.

Notes:

  • I didn't have assets folder by default.
  • Trying on Localhost:4200
  • Going to Localhost:4200/assets/images/bg.jpg in browser displays the picture.
  • If I put an online hosted image in url(), everything works.

Since there was no assets folder in my root, I created one in src folder.

Structure:

► node_modules
▼ src
   ▼ app
      ▼ components
         ▼ home
           home.component.html
           home.component.scss
           home.component.spec.ts
           home.component.ts
   ▼ assets
      ▼ images
         ▼ bg.jpg

.angular-cli.json

  "assets": [
    "assets",
    "images",
    "favicon.ico"
  ],

home.component.scss

.homeBg {
  background-image: url('../../../assets/images/bg.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  width: 100vw;
  height: 100vh;
}

Can someone please help me and tell me what I did wrong? I'm losing my mind for almost 3 hours trying to figure this out.

Thanks in advance.

Valine answered 19/3, 2018 at 1:0 Comment(3)
Are the browser dev tools showing a 404 error for bg.jpg. If so, what's the requested url?Apiary
url('bg.507198febc2a9a98bcf6.jpg') - Invalid property value.Valine
Hmm, yes. Seems that removing -image from background-image fixed it.Valine
V
4

Solved here.

This is because you've also specified "no-repeat" along with your background image. Alter your code to:

background: url('../../../assets/images/bg.jpg') no-repeat center center fixed;

Thanks @Mike Lun for reminding me to check the actual error.

Valine answered 19/3, 2018 at 2:37 Comment(0)
S
0

For those who are working with Ionic you need to set the background property this way:

ion-content {
  --background: url("/assets/images/my-background.jpeg") no-repeat center center /
    cover;
}

That two dashes before the background worked for me

Steersman answered 1/8, 2023 at 15:23 Comment(0)
D
0

I had the exact same issue.

I tried the solution above but it didn't work. It turns out that for me, I used a path like this: '/static/resources/img/cancel.png'. Changing it to '../../assets/static/resources/img/cancel.png' and then background back to background-image worked.

Delorisdelorme answered 17/3, 2024 at 3:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.