自动居中并保持Div。中的图像的纵横比 [英] Auto Center and Keep Aspect Ratio of Image in Div

查看:200
本文介绍了自动居中并保持Div。中的图像的纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使一个图像在一个div中心,同时保持宽高比 - 我使用这个代码,但不知何故,它不会对齐中心(顶部/底部中心)的项目。如果可能只使用CSS。



图片的大小不知道,因为它使用了最大宽度!



JSfiddle: http://jsfiddle.net/L41wpza6/2/

  #imageHolder {
width:400px;
height:400px;
line-height:400px;
background-color:#CCCCCC;
}

#imageHolder img {
max-width:100%;
max-height:100%;
display:block;
margin:0 auto;
vertical-align:middle;

}



解决方案

JSFiddle - DEMO



您应该使用 display:inline-block; 到 #imageHolder img 到vertical-align中间。



CSS display inline-block属性允许元素像内联元素一样流动,但是尊重属性(如宽度),如块元素,并且您可以使用display Inline-block设置vertical-align中间。



HTML


< img src =http://www.discoverjb.com/wp-content/uploads/2014/07/IMG_1399.jpg>
< / div>

CSS:

  #imageHolder {
width:400px;
height:400px;
line-height:400px;
background-color:#CCCCCC;
}
#imageHolder img {
max-width:100%;
max-height:100%;
display:inline-block; / *而不是display:block; * /
margin:0 auto;
vertical-align:middle;
}


I m trying to center an image in a div while keeping the aspect ratio - I m using this code but somehow its not aligning the item in the center (top/bottom center). If possible using only CSS.

The size of the image is not known since its using max widths!

JSfiddle: http://jsfiddle.net/L41wpza6/2/

#imageHolder {
width: 400px;
height: 400px;
line-height: 400px;
background-color:#CCCCCC;
}

#imageHolder img {
 max-width: 100%;
  max-height:100%;
  display: block;
  margin: 0 auto;
  vertical-align: middle;

}

Any help is appreciated! I am not sure what I am missing to make this work.

解决方案

JSFiddle - DEMO

You should use display: inline-block; to #imageHolder img to vertical-align middle.

CSS display inline-block property allows elements to flow like inline elements but respect properties, such as width, like block elements and you can use display Inline-block to set vertical-align middle.

HTML:

<div id="imageHolder">
    <img src="http://www.discoverjb.com/wp-content/uploads/2014/07/IMG_1399.jpg">
</div>

CSS:

#imageHolder {
    width: 400px;
    height: 400px;
    line-height: 400px;
    background-color:#CCCCCC;
}
#imageHolder img {
    max-width: 100%;
    max-height:100%;
    display: inline-block; /* Instead of display: block; */
    margin: 0 auto;
    vertical-align: middle;
}

这篇关于自动居中并保持Div。中的图像的纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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