I previously answered your SO question, so I will use that as a reference for my response to this question. You can view the updated Stackblitz with images of varying widths and heights.
https://i.sstatic.net/EqXvf.png
EDIT: I have made adjustments to the answer and Stackblitz to display 5 elements in a row.
Explanation
To maintain consistent image height, I added the "image" class to the <img>
tag (you could also apply the CSS directly to the img
tag using .product img{...}
).
<img class="image" mat-card-image src="{{product.picture.url}}" alt="photo">
I then applied the following CSS:
.image{
height: 150px; /* adjust as needed */
object-fit: contain;
}
By using object-fit: contain
, the image will always be properly scaled and fully visible within the available area.
Note that object-fit
is currently only fully supported by certain browsers.
EDIT:
To achieve 5 elements in each row, you need to adjust the fxLayoutGap
and calculate the width for each element using the fxFlex
attribute. Modify your code as follows:
<div class="container" fxLayout="row wrap" fxLayoutAlign="center center" fxLayoutGap="20px">
<!-- Add addProduct-button outside loop -->
<mat-card fxFlex="0 1 calc(20% - 20px)" (click)="addProduct()" class="product">
...
</mat-card>
<!-- loop over the products -->
<mat-card fxFlex="0 1 calc(20% - 20px)" *ngFor="let product of products; let i = index" class="product">
...
</mat-card>
</div>
Adjust the value of 20px set on the fxLayoutGap
and within the calculation of fxFlex
based on your preferences.
With these values set, remember to apply a min-width value to prevent all elements from becoming smaller in width without wrapping:
.product{
min-width: 180px; /* adjust as desired */
min-height: 250px;
margin-bottom: 20px; /* same as fxLayoutGap for even distribution */
}
EDIT 2
To ensure the first element matches the height of the others, adjust the (min-)height
properties of the .product CSS-class to match the tallest product's height.
EDIT 3 (to address edit 2 of the question)
Since your question hasn't been marked as answered yet, I have modified the code provided in your edit #2 to achieve your desired design: stackblitz
Changes made include:
- Updated the
fxLayoutAlign
on the container to "space-evenly stretch"
instead of fxLayoutAlign="start start"
for even distribution and consistent height.
- Removed all instances of
fxFlexFill
- Added
fxFlex
to the mat-card-content
- Removed the height property from the .product CSS-class
If there is an issue with the border on the left side, it may be due to the container being too close to the left edge of the browser window. I have adjusted the container CSS in the stackblitz as well.