I’m trying to center an element. The element may change width, therefore I cannot use the CSS method of margin: 0 auto.
Here is my code:
$.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();
Unfortunately, this isn’t working. Can you help me figure out why? Should I be using absolute positioning?
Thanks.
No need for all this..
since you are making the sub-elements (the
li) to be inline-block, just set the container#navto havetext-align:center.and do not set any margins at all..