简体   繁体   English

在Angular2中将封装设置为无设置背景

[英]Setting background in Angular2 with encapsulation set as none

I'm trying to set an image to the background of an entire page the following way: 我正在尝试通过以下方式将图像设置为整个页面的背景:

app.component.html app.component.html

<div [ngStyle]="{'background-image': 'url(' + somePhoto + ')'}">
  <h1>
    Hello, world
  </h1>
</div>

app.component.ts (note: encapsulation set to none) app.component.ts(注意:封装设置为none)

import { Component, ViewEncapsulation } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
    console.log('hello, world');
  }
}

app.component.css app.component.css

body {
   background-repeat: no-repeat;
   background-size: cover;
   background-position: center center;
   background-attachment: fixed;
 }

The problem is, when using [ngStyle] the image only covers the header portion of the page. 问题是,当使用[ngStyle]时,图像仅覆盖页面的页眉部分。

If instead of ngStyle, I select the body directly with something like: 如果不是ngStyle,我将直接选择类似以下内容的主体:

 document.body.style.backgroundImage = 'url(someimage.jpg)';

The image covers the entire page, which is what I want to happen. 该图像覆盖了整个页面,这就是我想要发生的事情。 But I've been told selecting the body directly is bad practice. 但是有人告诉我直接选择身体是不好的做法。

How can I get [ngStyle] (or anything else) to create a background image that covers an entire page? 如何获得[ngStyle](或其他任何东西)来创建覆盖整个页面的背景图像?

Thanks 谢谢

You could cover the body with a div of your template, and fill it with the background image, as shown in this stackblitz : 您可以用一个div模板覆盖主体,并用背景图像填充它,如以下stackblitz所示:

app.component.html app.component.html

<div class="outerDiv" [ngStyle]="{'background-image': 'url(' + somePhoto + ')'}">
    <div>
        <h1>
            Hello, world!
        </h1>
    </div>
</div>

app.component.css app.component.css

.outerDiv {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
    background-attachment: fixed;  
}

styles.css: styles.css:

html,
body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

Note: I added an outer div to allow setting overflow: hidden . 注意:我添加了一个外部div以允许设置overflow: hidden Without that style attribute, the default margin of the h1 element prevented the div from filling the top of the body (at least in Chrome on Windows). 如果没有该样式属性,则h1元素的默认边距将阻止div填充主体的顶部(至少在Windows的Chrome中是这样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM