2012-05-13 50 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;