tags:

views:

170

answers:

2

I want to display a DIV inside a table cell which is too narrow for it. I'm using overflow:hidden to allow the div to spill out one side of the table cell but now I want to center it so that it spills out a wee bit on both sides insdead of alot on one side.

How do I horizontally center a DIV inside a TD which is too narrow for the DIV?

A: 

If your layout is fixed you could always absolutely position your div e.g.

#myDiv
{
    position: absolute;
    left: 20px;
}

or if the div need to be relative to the current position of the table cell:

#myDiv
{
    position: relative;
    left: 20px;
}

There is also top, right and bottom css attributes for positioning. These can be a positive or negative number based on the direction needed.

w4ymo
Thanks, this will mostly work - I'm not always sure I can guarantee the size of the child DIV tho so centering is what I'm really after
domspurling
I'm not too sure then. If you need something dynamic like that you could try executing some jQuery after the page has loaded and apply some custom styling directly do the div using the JavaScript onLoad event? Not too sure if that approach would work though.
w4ymo
+1  A: 

make your div have an inner div:

<td><div class="outer">
    <div class="inner></div>
</div></td> <!--close cell>

Then apply a 50% margin-left to div.outer and a negative 50% margin-left to div.inner. This should position the div perfectly centered horizontally in the cell.

Concept:

let's imagine that the table cell is 20px wide and the div's are 22px wide. the div.outer left edge of the box will be pushed to a pixel position of 10 within the table cell. Then with a -50% margin div.inner will be pulled back to the left 11 pixels positioning it one pixel outside to the left of the table cell and inherently overflowing 1 pixel on the right.