0

I'm working on an Angular 18 project, and I need to set a background image for my application. However, I'm not sure how to properly reference and display the image in the app. I've tried a few different approaches, but nothing seems to work.

I placed my image (background.jpg) in the src/assets/ folder.

I used CSS in my component's CSS file

What happens: The background image doesn’t show up, and the is just a blank area without any background.

I’ve also tried using the global styles.css file with the following, but it doesn’t work either:

What I want to achieve: I want the background image to cover the entire screen and remain responsive across different devices. Ideally, I want the background to be applied globally (to the body) or to a specific component, depending on the best approach.

What I expect: The background image should display as expected when the page loads, covering the entire background of the app.

Additional Information: I’m using Angular 18. I’ve checked the file path, and the image is located at src/assets/images/background.jpg.

1 Answer 1

2

Make sure you have the assets folder added to the angular.json file, in latest versions of angular, there will be a public folder, where you can store the assets.

angular.json

      "options": {
        "assets": ["src/assets"],
        "index": "src/index.html",

After this, restart the server, so that the app recognizes the added paths.


Finally open the styles.scss or styles.css (these styles are applied globally throughout the application, for component styles they are scoped to only the component they are applied to).

Then add the below CSS. We simply set the dimensions of the html and body tag and configure the URL for the background image of the body. I use background-size to make sure the image fills the entire available screen. But you need to play around with the CSS properties to find what fits for you.

html,
body {
  margin: 0;
  min-height: 100vh;
  width: 100vw;
}

body {
  background-image: url('/assets/background.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.