How do you center an image in a specified area, without resizing the image?

I want to center an image in an area, without resizing... I am using HTML.

Example:

I have an image <img src='img1.png' width='64' height='64'> - the image is actually 64x64. It displays perfectly.

Now, I have another image <img src='img2.png' width='64' height='64'> however, the image is not as big as it should be, its 32x32 - what happens here is it resizes the image to 64x64 and makes it look like $%^&.

How do I make images smaller then the desired width and height centered in the 'img' area without any resizing what so ever?


What you will need is something like this:

<div class="box">
    <img src="whatever size image you'd like" />
</div>

And for the styling (in an external stylesheet, natch) you'd apply:

/* Image centering */
div.box {
    border: 1px black solid;
    height: 64px;
    width: 64px;
    background: #444;
    display: table-cell;
    vertical-align: middle;
}
.box img {
    display:block;
    margin: 0px auto;
}

This works for images with dimensions <= 64x64px, and is easily modifiable to work with larger pics. The key elements here are

  • set dimensions on the div
  • display as a table-cell (allows vertical align)
  • vertical align (aligns on the Y-axis w/out weird hacks)
  • display:block on the img element
  • margin: auto centers the image laterally

  • 没有IE不友好display:table-cell解决方案display:table-cell

    <!DOCTYPE html>
    <style>
    div {
      line-height:64px; /* that's the secret sauce */
      text-align:center;
      width:64px; height:64px;
    }
    img {vertical-align:middle}
    </style>
    <div><img …></div>
    

    You could try putting the image inside a DIV that is 64x64 and not specifying the image dimensions. Then you could style the div so its contents are centered and any overflow is hidden.

    链接地址: http://www.djcxy.com/p/61140.html

    上一篇: PHP保存图像文件

    下一篇: 如何在指定区域对图像进行居中,而不调整图像大小?