将图片居中放置在div中? [英] Center an image inside a div?

查看:132
本文介绍了将图片居中放置在div中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的div中有一个图片

 < div>< img />< div& 

图片是动态的,没有固定大小。 div的大小为 200px x 200px 。图像大小未预先知道。如果图片的大小大于 190px×190px ,请将其设置为 190px 190px (即 max-width:190px max-height:190px )。如何满足这些需求的图像中心?我需要一个在Internet Explorer 7中使用的解决方案。



解决方案这里此处无法应用于我的问题,因为


  1. 不确定图片会少


  2. 没有互联网资源管理器; 7支持。


(有些问题在Stack Overflow有问题, ,因此它们不适用于此特定问题。)

解决方案

解决方案是更改 div 到表中。通常,您不应使用表进行定位,但是对于旧的非标准兼容的浏览器,有时这是唯一的选择。 此处的演示。对于记录,这也适用于Internet Explorer 6。



代码:



CSS

  #theDiv 
{
width:200px;
height:200px;
text-align:center;
vertical-align:middle;
}
#theImg
{
max-width:190px;
max-height:190px;
}

HTML
$ b

 < table id =theDivstyle =border:solid 1px#000> 
< tr>
< td>
< img id =theImgsrc =http://cdn1.sbnation.com/community_logos/9156/gangreen-small.jpg/>
< / td>
< / tr>
< / table>


I have an image inside a div like this

<div><img /><div>

The image is dynamic of no fixed size. The div is of size 200px by 200px. The image size is not known beforehand. If the size of the image is greater than 190px by 190px, set it to 190px by 190px (that is, max-width:190px, max-height:190px). How can I center the image with these needs satisfied? I need a solution working in Internet Explorer 7 too.

The solution here and here can not be applied to my problem because

  1. It is not certain that the image would be less than 200 pixels.

  2. I want horizontal alignment too.

  3. No Internet Explorer 7 support.

(Some questions have been asked on Stack Overflow regarding the same, but my scenario is different, so they are not applicable for this particular problem.)

解决方案

The solution is to change the div into a table. Normally, you shouldn't use tables for positioning, but when it comes to older non-standards-compliant browsers, sometimes that's the only choice. Demonstration here. For the record, this works on Internet Explorer 6, as well.

Code:

CSS

#theDiv
{
    width: 200px;
    height: 200px;
    text-align: center;
    vertical-align: middle;
}
#theImg
{
    max-width: 190px;
    max-height: 190px;
}​

​HTML

<table id="theDiv" style="border: solid 1px #000">
    <tr>
        <td>
    <img id="theImg" src="http://cdn1.sbnation.com/community_logos/9156/gangreen-small.jpg" />
        </td>
    </tr>
</table>

这篇关于将图片居中放置在div中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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