首页 > 解决方案 > css:绝对定位的 div 在父级中具有错误的大小

问题描述

我正在尝试将图像(实际上是精灵表)放在 css-grid 中。
为了能够对 sprite-sheet 进行 css 动画处理,我必须将其位置定义为“绝对”。我设法用一个非常简单的代码复制了我的问题:

首先,我有一个 sprite-sheet 组件,它包含 sprite-sheet 和 compo-image 组件,它应该模拟另一个包含此 sprite-sheet 的组件

sprite-sheet.component.ts:

import { Component } from '@angular/core';

    @Component({
      selector: 'sprite-sheet',
      styleUrls: ['./sprite-sheet.component.scss'],
      templateUrl: './sprite-sheet.component.html',
    })
    export class SpriteSheetComponent {
      constructor() {
      }
    }

sprite-sheet.component.html

<div></div>

sprite-sheet.component.css

:host {
  height: 100%;
  width: 100%;
}

div
{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  background-repeat: no-repeat !important;
  background-position-x: 0%;
  background-image: url('/assets/icon/favicon.png')
}

带有 image.ts 的组件

import { Component } from "@angular/core";

@Component({
    selector: 'compo-image',
    templateUrl: `./component-with-image.html`,
    styleUrls: ['./component-with-image.css']
})
export class ComponentWithImage {
}

带有图像的组件.html

带有图像的组件.css

div {
    height: 100%;
    width: 100%;
}

然后我尝试在我的应用程序中显示此图像:

带有图像的组件.html

<div>
  some-text
</div>
<div> <!-- should be a css grid -->
  <compo-image></compo-image>
</div>

app.component.css

div {
    width: 100px;
    height: 100px;
}

compo-image {
    width: 100%;
    height: 100%;
}

但这就是我得到的: 在此处输入图像描述

很酷,这是因为我的绝对定位图像是相对于根组件的,因为我没有指定其他组件的位置。

所以我添加了一个名为 sprite-sheet2 的包装器组件来拥有一个“相对”位置并托管真正的 sprite-sheet 组件。

sprite-sheet.component2.ts

import { Component } from '@angular/core';

@Component({
  selector: 'sprite-sheet2',
  styleUrls: ['./sprite-sheet.component2.scss'],
  templateUrl: './sprite-sheet.component2.html',
})
export class SpriteSheetComponent2 {
  constructor() {
  }
}

sprite-sheet.component2.ts

:host {
    position: relative;
    height: 100%;
    width: 100%;
}

sprite-sheet {
    height: 100%;
    width: 100%;
}

sprite-sheet2.component2.html

<sprite-sheet></sprite-sheet>

但后来我明白了: 在此处输入图像描述

sprite-sheet2 上面的所有内容都定义了宽度和高度,但 sprite-sheet2 及其包含的所有内容都有 0x0 大小,即使这些组件的宽度和高度 = 100%。

我究竟做错了什么?

标签: htmlcssangular

解决方案


Angular 组件host没有默认显示display:block,因此您需要自己分配它。

:host {
    display: block; // or anything else
    position: relative;
    height: 100%;
    width: 100%;
}

但您可以在 angular.json 中设置设置,为使用ng g c XXXX命令生成的新组件分配默认显示。

"schematics": {
    "@schematics/angular:component": {
      "displayBlock": true
   }
 }

相关问题:

Angular 组件默认样式 css 显示块


推荐阅读