如果图像宽于其容器宽度,如何对其进行居中? [英] How do I center an image if it's wider than its container?

查看:102
本文介绍了如果图像宽于其容器宽度,如何对其进行居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,您可以使用 display:block; margin:auto ,但如果图像大于容器,它会溢出到右边。如何让它平均地溢出到双方?容器的宽度是固定的和已知的。

p>

 < div class =image-container> 
< img src =http://www.google.com/images/logo.gifheight =100/>
< / div>

  .image-container {
width:150px;
border:solid 1px red;
margin:100px;
}

.image-container img {
border:solid 1px green;
}

jQuery / p>

  $(image-container> img)。each(function(i,img){
$ img).css({
position:relative,
left:($(img).parent()。width() - $(img).width())/ 2
});
});



请参阅jsFiddle: http://jsfiddle.net/4eYX9/30/


Normally, you center images with display: block; margin: auto, but if the image is larger than the container, it overflows to the right. How do I make it overflow to the both sides equally? The width of the container is fixed and known. The width of the image is unknown.

解决方案

HTML

​<div class="image-container">
  <img src="http://www.google.com/images/logo.gif" height="100" />
</div>​

CSS

.image-container {
    width: 150px;
    border: solid 1px red;
    margin:100px;
}

.image-container img {
    border: solid 1px green;
}

jQuery

$(".image-container>img").each(function(i, img) {
    $(img).css({
        position: "relative",
        left: ($(img).parent().width() - $(img).width()) / 2
    });
});

See it on jsFiddle: http://jsfiddle.net/4eYX9/30/

这篇关于如果图像宽于其容器宽度,如何对其进行居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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