AncientToaster
AncientToaster

Reputation: 205

On a webpage html,css consisting only of an image, fit image to viewport and center horizontally and vertically

This is for a very simple throwaway webpage, so inline CSS is if anything preferred over proper/pretty CSS. The use case is pretty simple: Take a large image (the images are 2100 px wide by 3000 px high), and ensure it always resizes to 90% viewport size, and that the image is always centered vertically and horizontally regardless of viewport size. Needs to be a pure HTML/CSS solution (no javascript/jquery). The page contains no other content except these images (which are wrapped in <a href> tags and link to another page).

I've been hacking around with all sorts of variations on position:absolute, tables, divs, etc but can't seem to put something together that matches my use case.

Upvotes: 1

Views: 52

Answers (1)

Laura
Laura

Reputation: 3373

Just position them absolute with 0 for all sides and set margin to auto. You might need to set this on the surrounding link (or generally the outmost inline element). No problem inlining this, if really necessary, though wouldn't recommend.

img {
  max-width: 90vw;
  max-height: 90vh;
  
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  
  margin: auto;
}
<img src="http://via.placeholder.com/2100x3000">

Upvotes: 2

Related Questions