zrajm zrajm - 5 months ago 9
HTML Question

Center table, even if it is wider than parent container

I have a scenario in which the width of the HTML page is limited (with

) so that the text on the page doesn't become too wide (and hard to read).

I also have some data presented in tables (which are centered), which works fine, as long as the table fit inside the parent container. But sometimes a table becomes wider than the parent element, at which point it stops being centered and instead becomes aligned to the left.

Is there a way to center a table so that it stays centered even if it overflows its parent?

Given that my HTML looks like this, what CSS would be required to accomplish this?

<div class=content>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>

BTW. It might be obvious, but I'm only talking about horizontal centering here.

Here's a fiddle with my scenario: http://jsfiddle.net/zrajm/tnAS3/


CSS margin: 0 auto; only works as long as the table fits inside its parent element, if the table grows larger than that it becomes left aligned.

In order to center a table that is wider than its parent one need to set a negative left margin. If one knows the exact dimensions of the table, this can be done directly in CSS (using something like margin-left: -130px). If the width of the table can vary, however, the only way to achieve this is to use Javascript to adjust the left margin.

(Below code assumes jQuery, and the HTML structure described in the question.)

var contentWidth = $('.content').width();
$('table').each(function (i, table) {
    var tableWidth, margin;
    table = $(table);
    tableWidth = table.width();
    if (tableWidth > contentWidth) {
        margin = (tableWidth - contentWidth) / 2;
        table.css('margin-left', '-' + margin + 'px');

The above script will look for tables wider than .content, and modify only their left margins.

(There is also a fiddle: http://jsfiddle.net/zrajm/tnAS3/2/)