views:

34

answers:

3

I have a single column layout where the column is a centered div with a fixed width. I want to place a wider div within the column which overflows it's parents, but center it within the parent. Conceptually something like the following:

<div style="width: 100px; margin: 0 auto; overflow:visible;" id="parent">
    <div style="width: 400px; margin 0 auto;" id="child"></div>
</div>

The centering works as long as the child div is thinner than its parent, but once it gets larger, it always aligns left with the parent for some reason.

A: 

I am not 100% sure but try giving the parent element a position set to relative and child absolute and then set top, left and width/height properties for the child div accordingly.

Sarfraz
The problem with absolutely positioning it is that it's removed from the normal flow model and elements will appear under it. Is there a way to resume the normal flow model after an absolutely positioned element?
Sam Gibson
+1  A: 

I've made a jsFiddle solution

When an element overflows his parent, it is normal behaviour that it only overflows to the right. When you, for example, have a site that is wider then the viewport, you never have to scroll left, but only to the right. This solution is based on a absolute centered div, with a negative left margin (that value is the half of his own width). So if you know the width of this element, this solution should be fine.

Tested in FF 3.6, IE7 and IE8

Justus Romijn
I want to treat the inner div as a flowable object, though. Is there a way to resume the normal flow model after the element is made absolutely positioned?
Sam Gibson
I've updated the jsFiddle code: [click here](http://jsfiddle.net/4VrMv/3/)Use relative positioning to keep the flow (so the height of the child element stretches the parent element)
Justus Romijn
Precisely what I was looking for. Thanks.
Sam Gibson
A: 

I made a variation of Justus' solution. Instead of relative positioning, I used a negative margin of 50% in the inner element.

#wrapper {
    margin: 0 auto;
    padding: 10px 0 10px;
    width: 200px;
    background-color: #eee;
}
#child {
    margin: 0 -50%;
    width: 400px;
    background-color: #ddd;
}

This way you don't need to know the element sizes ahead of time.

Scott Robinson
hmm this doesn't work for me though. When I use this code and make the #child smaller or wider, the centering goes wrong...
Justus Romijn