Joseph Szymborski Joseph Szymborski - 5 months ago 20
CSS Question

Offset div from center

I'm trying to position a div x amount of pixels to the right of the center of the page. The div would therefore be relative to the center.

So far, I've tried something stupid like

margin:0 auto;
margin-left:20px;


But you don't need to test that in a browser to know it wouldn't work.

Thanks in advance for any help.

Answer

I'd try using two DIVs, one inside another. Something like this:

<div class="outer">
    <div class="inner">Hello, world!</div>
</div>

.outer {
    width: 1px; /* Or zero, or something very small */
    margin: auto;
    overflow: visible;
    background: red; /* A color just for debug */
}
.inner {
    margin-left: 20px;
    background: yellow; /* A color just for debug */
    width: 100px; /* Depending on the desired effect, width might be needed */
}

See this example live at jsfiddle.

The outer div would be horizontally centered as per this question/answer: How to center DIV in DIV?

Then, the inner diff is just moved 20 pixels to the right, using a margin.

Note that, if you leave width as auto, the width will be zero, and it might not be what you want.