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

删除回忆录丶 提交于 2019-12-24 10:44:54

问题


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.


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/46577445/how-to-center-image-when-its-smaller-than-parent-and-put-in-top-left-corner-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!