-2

I have a square image (for instagram) - 1080x1080 pixels.

I need to center the image and resize the image according with the resolution. If resolution is 1920x1080 - then I have a image with 1080x1080.

If the resolution is 1280x720 - I will have 720x720.

I tried:

img {
    display: block;
    margin: auto;
    width: 50%;
}

Works fine to center the image - but the image doesn't resize correctly.

VXp
  • 11,598
  • 6
  • 31
  • 46
DANIEL
  • 515
  • 7
  • 20
  • How about `width: 100vh` – Tyler Roper Nov 21 '17 at 22:25
  • If you use an background image you could set `background-size: contain;` (as big as possible, no cutting, keeping aspect ratio) example: https://jsfiddle.net/2vq5extx/ – Roland Starke Nov 21 '17 at 22:31
  • hi @Santi ! your solution fits perfectly! but I have a issue now.. On desktop ok Screens are WIDE - then the width is the large side. but When I try your solution on tablets or cellphones, with the height large than width - works but the image is cutted on the right side. tks!! – DANIEL Nov 21 '17 at 22:59
  • So essentially, you need the image to be the biggest, fully-visible square possible at any given resolution? I think VXp's solution below, as well as @RolandStarke's above, satisfy that requirement. Mine was based on the assumption that you were always looking to reduce the width. – Tyler Roper Nov 21 '17 at 23:03

2 Answers2

3

You can do it like this (bare minimum):

html, body {margin: 0; height: 100%}

img {
  display: block; /* removes bottom margin/whitespace */
  margin: 0 auto; /* you probably only want to center it horizontally */
  max-width: 100%; /* horizontally responsive */
  max-height: 100%; /* vertically responsive */
}
<img src="http://placehold.it/1080x1080" alt="img">
VXp
  • 11,598
  • 6
  • 31
  • 46
1

If the height should always be the same as the full screen height, you can use height: 100% and width: auto, together with margin: 0 auto which will center it horizontally.

Johannes
  • 64,305
  • 18
  • 73
  • 130