CSS中心任何图像在div [英] CSS center any image in div

查看:157
本文介绍了CSS中心任何图像在div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 div with width:300px height:200px

我想让此 div 中的任何图片在水平和垂直方向居中,无论图片是大于还是小于 div ;



对于较小的图片 margin:0 auto 但是更高的图像向右突出并且不居中。



对于更大的图片,此功能适用:

  height:100% 
top:50%;
left:50%;
transform:translate(-50%,-50%);

我找不到任何组合,没有找到任何解决方案如何完美地中心这

解决方案

添加 position:absolute img position:relative div



  .el {position:relative; width:100px; height:100px; border:1px solid black; margin:50px 150px;} img {opacity:0.4; top:50%;左:50%; transform:translate(-50%,-50%); position:absolute;}  

 < div class = > < img src =http://placehold.it/350x150> < img src =http://placehold.it/50x50/000000/ffffff>< / div>  

/ p>

@QUESTION AUTOR EDIT:我也添加了 max-width:100%; max-height:100%,可以完美工作! (特别是对于设计风格)


Lets say I have div with width: 300px and height: 200px
I want any image inside this div to be centered both horizontally and vertically no matter if image is bigger or smaller than div;

For smaller images margin: 0 auto works well but higher image protrude to the right and isn't centered.

For bigger images this works:

height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

I couldn't find any combination of those and didn't find any solution how to perfectly center this image.

解决方案

Add position: absolute to img and position: relative to div

.el {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 50px 150px;
}
img {
  opacity: 0.4;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
}

<div class="el">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/50x50/000000/ffffff">
</div>

@QUESTION AUTOR EDIT: i also added max-width: 100%; max-height:100% and works perfectly! (especially for reponsive styling)

这篇关于CSS中心任何图像在div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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