skip to Main Content

I have angular image which I would like to keep in center when the browser width changes. ie the left and right of the image are cropped but image is focused. Currently its fixed top left corner.

Here is stackblitz
https://angular-template-tpjdhp.stackblitz.io

My code:

<div
  [style.background]="
    'url(https://upload.wikimedia.org/wikipedia/commons/b/b6/Santorin_%28GR%29%2C_Exomytis%2C_Vlychada_Beach_--_2017_--_2999_%28bw%29.jpg)'
  "
  class="home-custom-image"
></div>

Css

.home-custom-image {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
  margin: 5px;
  margin-top: 10px;
  border-radius: 8px;
  height: 469px;
  text-align: center;
  background-position: center center;
  background-repeat: no-repeat;
  background-size:  cover;
}

2

Answers


  1. Use [style.background-image] instead of [style.background]

    You are overwriting your background-position property when you use the shorthand like this.

    enter image description here

    Login or Signup to reply.
  2. You can simply use [ngStyle] and reduce your code for css as below

    <div class="home-custom-image" [ngStyle]="{'background': 'url(https://upload.wikimedia.org/wikipedia/commons/b/b6/Santorin_%28GR%29%2C_Exomytis%2C_Vlychada_Beach_--_2017_--_2999_%28bw%29.jpg) center center / cover no-repeat'}">
    
    </div>
    

    CSS

    .home-custom-image {
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
      margin: 5px;
      margin-top: 10px;
      border-radius: 8px;
      height: 469px;
      text-align: center;
    }
    

    And to make dymaic image you can use code as below

    <div class="home-custom-image" [ngStyle]="{'background': 'url(' + imageUrl + ')  center center / cover no-repeat'}">
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search