我正在尝试使元素居中。元素可能会改变宽度,因此我不能使用margin: 0 auto
.
这是我的代码:
$.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();
不幸的是,这不起作用。你能帮我弄清楚为什么吗?我应该使用绝对定位吗?
谢谢。