html - 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%。
我究竟做错了什么?
解决方案
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
}
}
相关问题:
推荐阅读
- r - 我可以在地理地图上叠加 ggplot 热图吗?
- ethereum - (中间值).toBigNumber 不是函数
- javascript - HTML5 Canvas 弹跳球从房间里的免费线上
- wordpress - 激活 WPML 插件后 Elementor 页眉和页脚消失
- c - 从一行中读取多个字符串。检测无效输入
- ios - 使用真实设备数量和 iOS 版本测试 iOS SDK 公共功能的最佳方法应该是什么?
- python - 字符串变量似乎在嵌套的 for 循环中重置
- html - 如何在引导导航栏中对齐元素
- go - 如何导入vscode路径
- react-native - 监听 Expo 推送通知