CSS center any image in div

旧巷老猫 提交于 2019-12-01 23:31:13

问题


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.


回答1:


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>



回答2:


Try this

div{
  display: flex;
  align-items: center;
  justify-content: center
}


来源:https://stackoverflow.com/questions/37485593/css-center-any-image-in-div

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