2012-05-13 49 views
0

我试图居中一个元素。该元素可能会改变宽度,因此我不能使用margin: 0 auto的CSS方法。用Jquery居中元素

这里是我的代码:

$.fn.center = function() { 
    $(this).css({ 
     'margin-left': ($(this).parent().innerWidth() - $(this).outerWidth())/2 + "px", 
     'margin-right': ($(this).parent().innerWidth() - $(this).outerWidth()) + ($(this).outerWidth()/2) + "px" 
    }); 
}; 
$('#nav').center(); 

不幸的是,这是行不通的。你能帮我弄清楚为什么?我应该使用绝对定位吗?

谢谢。

+1

显示[JS小提琴](http://jsfiddle.net/)或类似演示可能? –

+1

_这不是工作_是什么意思? – Andreas

+0

@davidthomas它的生活在一个tumblr网站即时通讯制作:http://dev-indiehaz.tumblr.com/应该集中在标题下的导航链接! – Harry

回答

2

不需要所有这些..

由于您将子元素(li)设置为内嵌块,因此只需将容器#nav设置为text-align:center即可。

,并在所有不设置任何空白..

+0

谢谢,这个作品! – Harry

0

它可以工作:

var space = ($(this).parent().width() - $(this).width)/2; 

$(this).css({marginLeft : space , marginRight : space}); 
0

要居中canvas元素与 'GameCanvas类' 的ID,包含一个div内的 '游戏' 的ID我最近使用:

$('#gameCanvas').css('margin-left', ($('#game').width() - $('#gameCanvas').width())/2); 

所以,如果你知道你的容器ID,用#this和'#game'替换'#gameCanvas'和你的容器ID

1

你可以定位你的元素position:absolute;,然后,用你的公式设定左侧位置。其他方法是定位元素position:relative;,并使用outerWidth来设置元素的宽度,然后将其定位margin:0 auto;