我試圖居中一個元素。該元素可能會改變寬度,因此我不能使用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();
不幸的是,這是行不通的。你能幫我弄清楚爲什麼?我應該使用絕對定位嗎?
謝謝。
顯示[JS小提琴](http://jsfiddle.net/)或類似演示可能? –
_這不是工作_是什麼意思? – Andreas
@davidthomas它的生活在一個tumblr網站即時通訊製作:http://dev-indiehaz.tumblr.com/應該集中在標題下的導航鏈接! – Harry