How to keep aspect ratio of a background-image? [duplicate]

Use background-size: cover; to cover the entire element, while maintaining the aspect ratio:

.background-1,
.background-2,
.background-3 {
  /* Set the background image, size, and position. */
  background-image: url('//via.placeholder.com/350x150');
  background-size: cover;
  background-position: center;

  /* Or, use the background shortcut. */
  background: url('//via.placeholder.com/350x150') center/cover;

  margin: 20px;
  border: 1px solid rgba(0, 0, 0, 0.3);
}

.background-1 {
  width: 300px;
  height: 200px;
}

.background-2 {
  width: 200px;
  height: 50px;
}

.background-3 {
  width: 100px;
  height: 200px;
}
<div class="background-1"></div>
<div class="background-2"></div>
<div class="background-3"></div>

If you want to display the entire image, while maintaining the aspect ratio, use background-size: contain; instead:

.background-1,
.background-2,
.background-3 {
  /* Set the background image, size, position, repeat, and color. */
  background-image: url('//via.placeholder.com/350x150');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #fbfbfb;

  /* Or, use the background shortcut. */
  background: #fbfbfb url('//via.placeholder.com/350x150') no-repeat center/contain;

  margin: 20px;
  border: 1px solid rgba(0, 0, 0, 0.3);
}

.background-1 {
  width: 300px;
  height: 200px;
}

.background-2 {
  width: 200px;
  height: 50px;
}

.background-3 {
  width: 100px;
  height: 200px;
}
<div class="background-1"></div>
<div class="background-2"></div>
<div class="background-3"></div>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)