当图片比父图片小时如何居中,当图片较大时如何放在左上角? [英] How to center image when it's smaller than parent and put in top left corner when it's bigger?

查看:54
本文介绍了当图片比父图片小时如何居中,当图片较大时如何放在左上角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的图片较小(例如100x100)并且其父级较大(例如200x200)时,我希望图像在父级中垂直和水平居中.

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.

但是,当图像比父图像(200x200)宽(例如300x100)时,我希望将其放置在父图像的左侧,并具有水平滚动条以滚动并查看整个图像.

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.

当图像比父图像高(例如100x300)时,我希望将其放置在父图像的顶部,并具有垂直滚动条以查看整个图像.

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.

我知道如何使用Javascript执行此操作,但是我需要CSS解决方案.

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

推荐答案

首先,将Flexbox及其justify-content/align-itemscenter一起使用应该可以,但不能这样做,因为它将创建一个当弹性项目较高时,在顶部/底部都溢出.

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

一种更好的方法(可以在浏览器中正常使用)是自动页边距,以及img周围的包装.

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

包装器的原因很简单,当img成为flex项时,跨浏览器的行为不一致.

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.

更新的代码笔

堆栈片段

.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>

这篇关于当图片比父图片小时如何居中,当图片较大时如何放在左上角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆