I'm new to web dev and am trying to use an image that I get from Contenful content as a cover image within a div without using an <img>
. It works well if I set it as a [src]
of an <img>
tag within my html file but as far as I could see, using it as an img tag:
<img [src]="blogPost.fields.featuredImage.fields.file.url" alt="">
dint give me the sizing and styling I got from using a div with css file styling:
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;
above I used the same image that exist on contentful but it looks more proportioned and sized as I want when i load it from my pc with a src url.
But since the image I want is from an *ngFor block: *ngFor="let blogPost of blogPosts.items"
i have no idea how to set it as a background image of a div
without using <img>
tag
here is the code I used:
<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>
This is want I want to try:
<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;}
So is it possible to use the resource im getting im my html *ngFor in my css file? or am I asking the right question when there is an alternative way?
You can bind blogPost.fields.featuredImage.fields.file.url
property to inline style background of div with img
class.
The following HTML code would work for you:
<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" [style.background]="'url(' + blogPost.fields.featuredImage.fields.file.url + ') center 50% fixed no-repeat'"></div>
</div>
</mat-grid-tile>
</div>
</mat-grid-list>