Tom
Tom

Reputation: 3034

How to center image when it's smaller than parent and put in top left corner when it's bigger?

When I have small image (eg. 100x100) and it's parent is bigger (eg. 200x200) then I want the image to be centered both vertically and horizontally in the parent.

But when image is wider (eg. 300x100) than the parent (200x200) I want it to be placed on the left side of the parent and have a horizontal scrollbar to scroll and see the whole image.

When image is higher (eg. 100x300) than the parent I want it to be placed at the top of the parent and have vertical scrollbar to be able to see the whole image.

I know how to do this in Javascript but I need a CSS solution.

Upvotes: 1

Views: 88

Answers (2)

Asons
Asons

Reputation: 87191

At first, using Flexbox and its justify-content/align-items with center should do it, but it doesn't, as it will create an overflow at i.e. both top/bottom when the flex item is higher.

Src: https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-center


A better approach, that will work properly cross browsers, would be auto margins, and a wrapper around the img.

The reason for the wrapper is simply that there is an inconsistent behavior cross browsers when it comes to an img being a flex item.

Updated codepen

Stack snippet

.box {
  width:300px;
  height:300px;
  border:1px red solid;
  overflow: auto;                 /*  changed so it only show scroll when needed  */
  display: flex;
  align-items: flex-start;        /*  IE need this  */
}
.box > div {
  margin: auto;
}
.box > div > img {
  display: block;
}
<div class="box">
  <div>
    <img src="https://unsplash.it/200/200" alt="">
  </div>
</div>

<div class="box">
  <div>
    <img src="https://unsplash.it/200/800" alt="">
  </div>
</div>

<div class="box">
  <div>
    <img src="https://unsplash.it/800/200" alt="">
  </div>
</div>

Upvotes: 1

Niles Tanner
Niles Tanner

Reputation: 4021

You probably just want to always center the image and it will align how you would like on it's own.

.box {
  width:300px;
  height:300px;
  border:1px red solid;
  overflow:scroll;
  display:flex;
  justify-content:center;
  align-items:center;
}

The most important part here is this:

display:flex;
justify-content:center;
align-items:center; 

It's these three lines will make it so any thing inside the 'box' will be centered vertically and horizontally.

Then you can add overflow:scroll; to allow for the scrolling you want.

Working example:

.box {
  width:300px;
  height:300px;
  border:1px red solid;
  overflow:scroll;
  display:flex;
  justify-content:center;
  align-items:center;
}
<div class="box">
  <img src="https://unsplash.it/200/200" alt="">
</div>

<div class="box">
  <img src="https://unsplash.it/200/500" alt=""> 
</div>

<div class="box">
  <img src="https://unsplash.it/500/200" alt="">
</div>

Upvotes: 3

Related Questions