如何在div中显示图像而不调整其大小

时间:2012-09-11 06:55:53

标签: jquery html css image

我有一个 160x160 像素的div。我想在这个div中显示图像。我想在没有调整大小的情况下在div中显示图像。

  • 如果图像小于div,则在不调整大小的情况下将图像显示在div的中心。
  • 如果图像较大,则div会在div中显示图像的中心部分而不调整其大小。

这个div就像现实世界中的窗口。您可以根据窗口大小从该窗口查看视图。

我想你能理解这个吗?

由于

6 个答案:

答案 0 :(得分:6)

只需使用这样的简单背景图片:

div {background:url(image.jpg) 50% 50% no-repeat; height:160px; width:160px}

如果你想使用实际的<img>,你可以这样做:

<div><img src="image.jpg" /></div>​​​​​​​​​​​​​

div {position:relative; text-align:center; overflow:hidden; height:160px; width:160px}
img {position:absolute; left:50%; margin-left:-250px}​

margin-left是图像宽度的一半 - 仅在您提前知道图像大小时才有效。如果您不知道,可以使用JavaScript获取图像大小吗?

答案 1 :(得分:3)

<div><img src="yourimage.jpg" /></div>

div{width:auto; margin:0 auto}
div img{max-width:100%}

max-width将最大宽度作为图像的原始大小。即使ig你调整窗口大小,你也可以用较小的图像看到效果。

答案 2 :(得分:1)

您也可以将图像设置为背景

background: url('image.png') no-repeat center center;

以下是一个示例:http://jsfiddle.net/H5U3H/

答案 3 :(得分:1)

我认为这就是你需要的......

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style type="text/css">
            #imageLoader{
                border:1px solid #B0B0B0;
                height:160px;
                width:160px;
                background-image: url('images/Science.png');
                background-position:center center;
                background-repeat:no-repeat;
                background-clip:content-box;
            }
        </style>
    </head>
    <body>
        <div id="imageLoader" style="">
        </div>
    </body>
</html>

相应地更改图像名称

这是我的 Fiddle

答案 4 :(得分:0)

执行此操作的最佳方法是将图像设置为div的背景图像。

div { 
    background: transparent url(path/to/image.jpg) no-repeat center 0; 
    width: 160px; 
    height: 160px; 
}

如果图像大于div,则会使图像居中,否则会在div的(水平)中心显示图像。

答案 5 :(得分:0)

我的看法是,您不需要使用transform / top / left来了解图像的宽度:

<div style=" overflow: hidden; width: 160px; height: 160px">
  <img src='https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' style="position: relative; left: 50%; top: 50%; transform: translate(-50%, -50%)"/>
</div>