Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit, scale and center image responsively to browser window (CSS)

How do I have an image, irrespective of portrait or landscape:

  • centered responsively both horizontally and vertically (remains centered as browser window is resized)
  • occupies a fixed fraction of the browser window, scaling responsively
  • preserves aspect ratio as browser window is resized
like image 852
Abhranil Das Avatar asked Apr 08 '15 23:04

Abhranil Das


People also ask

How do you scale an image to fit the screen in CSS?

Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.

How do you autofit an image in CSS?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.

How do you scale a proportionally image in CSS?

In that situation we can use CSS max-width or width to fit the image. Use max-width: 100% to limit the size but allow smaller image sizes, use width: 100% to always scale the image to fit the parent container width.


1 Answers

Here's a solution that satisfies all of the above with only basic CSS (no CSS3 required):

http://jsfiddle.net/dvidby0/sytj1uws/1/

HTML

<div class="container">
<!-- this is a landscape image-->
<img src="http://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"/>
<!--or use this portrait image; still works
<img src="http://upload.wikimedia.org/wikipedia/commons/9/9d/Britishblue.jpg"/>
-->

CSS

.container {
width: 80%;
height: 80%;
position: absolute;    
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
background-color: #aaa;
}

img {
max-width: 100%;
max-height: 100%;  
position: absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
}
like image 79
Abhranil Das Avatar answered Oct 12 '22 00:10

Abhranil Das