0

我正在尝试使元素居中。元素可能会改变宽度,因此我不能使用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();

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

谢谢。

4

4 回答 4

2

这一切都不需要。。

由于您正在将子元素(li)设置为内联块,因此只需将容器设置#nav为 have text-align:center

并且根本不设置任何边距..

于 2012-05-13T17:43:12.217 回答
1

您可以定位元素position:absolute;,然后使用公式设置左侧位置。另一种方法是定位元素position:relative;,并使用outerWidth设置元素的宽度,然后使用margin:0 auto;

于 2012-05-13T17:43:47.610 回答
0

它可能有效:

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

$(this).css({marginLeft : space , marginRight : space});
于 2012-05-13T17:39:15.240 回答
0

要将 id 为“gameCanvas”的画布元素居中,包含在我最近使用的 id 为“game”的 div 中:

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

因此,如果您知道您的容器 ID,请将“#gameCanvas”替换为“#game”,this并将“#game”替换为您的容器 ID

于 2012-05-13T17:41:06.350 回答