【问题标题】:Using *ngFor element within css to set image background在 css 中使用 *ngFor 元素设置图像背景
【发布时间】:2022-09-26 16:07:38
【问题描述】:

我是网络开发的新手,我正在尝试使用从内容丰富的内容中获得的图像作为 div 中的封面图像,而不使用<img>。如果我在我的 html 文件中将其设置为 <img> 标记的 [src] 效果很好,但据我所知,将其用作 img 标记: <img [src]=\"blogPost.fields.featuredImage.fields.file.url\" alt=\"\"> dint 给我使用带有 css 文件样式的 div 的大小和样式:

background: url(\'/assets/img/landscape3.jpg\') center 50% fixed no-repeat;
    -webkit-background-size: cover;
    -o-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    height: 50vh;
    padding-top: 15rem;

上面我使用了存在于 contentful 上的相同图像,但是当我使用 src url 从我的 pc 加载它时,它看起来更加比例和大小。

但由于我想要的图像来自 *ngFor 块:*ngFor=\"let blogPost of blogPosts.items\" 我不知道如何在不使用<img> 标签的情况下将其设置为div 的背景图像 这是我使用的代码:

<mat-grid-list cols=\"4\" gutterSize=\"1rem\" rowHeight=\"4:3.5\" class=\"main\"
  *ngIf=\"blogPosts$ | async as blogPosts\">
   <div *ngFor=\"let blogPost of blogPosts.items\">
      <mat-grid-tile *ngIf=\"blogPost.fields.category === \'Science & 
      Tech\'\">
   <div class=\"tile\">
     <div class=\"title\"><p>{{ blogPost.fields.title }}</p></div>
     <img [src]=\"blogPost.fields.featuredImage.fields.file.url\" alt=\"\">
    
   </div>
</mat-grid-tile>

这是我想尝试的:

<mat-grid-list cols=\"4\" gutterSize=\"1rem\" rowHeight=\"4:3.5\" class=\"main\"
*ngIf=\"blogPosts$ | async as blogPosts\">
<div class=\"for\" *ngFor=\"let blogPost of blogPosts.items\">
<mat-grid-tile *ngIf=\"blogPost.fields.category === \'Science & Tech\'\">
<div class=\"tile\">
<div class=\"title\"><p>{{ blogPost.fields.title }}</p></div>
<div class=\"img\"></div>
    
    
</div>
</mat-grid-tile>

CSS:

.img {
margin-top: 0px;
background: url(\'blogPost.fields.featuredImage.fields.file.url\') center 
50% fixed no-repeat;
-webkit-background-size: cover;
-o-background-size: cover;
-moz-background-size: cover;
background-size: cover center 50% fixed no-repeat;}

那么是否可以在我的 css 文件中使用获取我的 html *ngFor 的资源?还是当有替代方法时我在问正确的问题?

    标签: html css angular contentful


    【解决方案1】:

    您可以为此使用内联样式。这些是通过 HTML 标记属性赋予元素的样式属性。

    您应该在样式中提供默认或后备图像,并使用如下内联样式覆盖它:

    div {
      background-color: blue;
      height: 200px;
      width: 200px;
    }
    &lt;div style="background-image: url('/assets/img/landscape3.jpg');"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2013-03-05
      • 2013-12-19
      • 2010-11-23
      • 2010-10-05
      相关资源
      最近更新 更多