如何使图像居中,同时保持响应?

时间:2013-06-08 21:41:36

标签: javascript jquery css responsive-design image-scaling

嗨,请看看我的网站,下面是有问题的代码片段,我必须集中我的图像,因为我从来没有运气与css-html方法。问题是因为它设置为等待document.ready()有时会将我的所有图像放在右边。我已经尝试过window.load(),但是图像以较小的窗口大小在屏幕中央。还有人建议我试试

<div style="
  background: url('Assets/image.png') center center no-repeat;
  width: 100%;
  height: 500px;
 ">
 </div>

但是这会导致它失去响应能力。我四处搜索,我找不到解决方案,我只需要我的图像(和一个表格)保持居中,并使图像缩小窗口大小。

网站:http://bit.ly/11nAQJK

<script type="text/javascript"> //Centering Script


$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});


function updateContainer() {


(function ($) {
$.fn.vAlign = function() {
    return this.each(function(i){
    var h = $(this).height();
    var oh = $(this).outerHeight();
    var mt = (h + (oh - h)) / 2;    
    $(this).css("margin-top", "-" + mt + "px"); 
    $(this).css("top", "50%");
    $(this).css("position", "absolute");    
    }); 
};
})(jQuery);

(function ($) {
$.fn.hAlign = function() {
    return this.each(function(i){
    var w = $(this).width();
    var ow = $(this).outerWidth();  
    var ml = (w + (ow - w)) / 2;    
    $(this).css("margin-left", "-" + ml + "px");
    $(this).css("left", "50%");
    $(this).css("position", "absolute");
    });
};
})(jQuery);

5 个答案:

答案 0 :(得分:3)

删除整个脚本。把它放在你的CSS中。

img{
    display: block;
    margin: 0 auto;
}

答案 1 :(得分:0)

只是做

<style>
a{
display:block;
text-align:center;
}

</style>



<a href="Assets/OrderSheet.xls">
    <img src="Assets/OrderSheet.png" class="image">
</a>

无需重新定位

fiddle

答案 2 :(得分:0)

不需要js,CSS就好了。将图像设置为显示块,设置宽度和最大宽度加上自动余量。

img {
display: block;
width: 300px;
max-width: 100%;
margin: 0 auto;
}

答案 3 :(得分:0)

如果您不接受其他人建议的方法,我建议您使用em's。最好在任何地方使用它们,但您可以将它们应用于您的图像。

然后使用media queries扩展/缩小em's中指定值的所有元素,方法是更改​​不同屏幕尺寸的基础font-size

答案 4 :(得分:0)

以响应大小的元素为中心

/* element/id/class */ 
/* margin is 100 - width / 2 */

img {
width:34%;    
margin: 0 33%;
}
相关问题