[英]CSS centered image
I have one question about image centering. 我有一个关于图像居中的问题。
I have created this DEMO from codepen.io. 我已经从codepen.io创建了这个DEMO 。
In this demo you can see i have used background image for centering it looks good for me. 在此演示中,您可以看到我使用背景图像进行居中,这对我来说看起来很好。
The image normalize looking like this: NORMALIZE 图像标准化如下: NORMALIZE
The question is how can use img
tag instead of background
and change the html like: 问题是如何使用img
标签代替background
并更改html像这样:
<div class="centered-image">
<img src="IMAGE-URL"/>
</div>
Use display: flex
and let the img
tag have width:100%
. 使用display: flex
并让img
标签的width:100%
。 DEMO 演示
.centered-img{ width:540px; height:200px; margin:0px auto; margin-top:50px; display:flex; justify-content:center; align-items:center; overflow:hidden; } .centered-img img{ width: 100%; }
<div class="centered-img"> <img src="http://i.imgur.com/BXo4qAz.jpg" /> </div>
Vertical centering is most easily done with flex box. 垂直居中最容易通过弹性盒完成。 This will also center horizontally. 这也将水平居中。
.centered-image {
display: flex;
align-items: center;
justify-content: center;
}
You still need to set proportions on .centered-image
, because it would otherwise just stretch to the height of the image and there wouldn't be any vertical alignment happening. 您仍然需要在.centered-image
上设置比例,因为否则它将仅拉伸到图像的高度,并且不会发生任何垂直对齐。
Please check this example . 请检查此示例 。 I resized the image to demonstrate the aligning, even on smaller screens. 我调整了图像的大小以显示对齐方式,即使在较小的屏幕上也是如此。
try this: 尝试这个:
img{
display: block;
margin: 0 auto;
}
Please check the fiddle - https://jsfiddle.net/afelixj/k37125ux/ 请检查小提琴-https: //jsfiddle.net/afelixj/k37125ux/
html, body{
height: 100%;
}
.centering-image{
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.