How do I centre absolutely positioned content of unknown width?

goose picture goose · Feb 20, 2012 · Viewed 20k times · Source

Before someone asks me why the hell I would want to do this let me come straight out and tell you. That way one of you clever peeps out there can tell me a far better way...

I'm making a viewer for paintings which should stretch to fill the page, well 90% of the height of the screen to be precise. I want to fade the paintings in one over the other and want to center each of them in the middle of the screen.

To fade the paintings in over each other I need to position them 'absolute' to stop them from stacking. Here's where the trouble comes. Ever since I've set them to absolute, every method I use to center the containing div hasn't worked.

Part of the problem is that I'm not setting any width for the paintings as I want them to dynamically size themselves to fill 90% of the user's screen.

I've found a hundreds of methods for centering absolute content and believe I might need to shrink wrap the containing div. However I've not had any success as of yet.

HTML-

<div id="viewer_div">
    <img src="" id="first" />
    <img id="second" class="hidden"/>
</div>

Style Sheet

#viewer_div {
        width:1264px;
}


img {
    height:90%;
    display:block;
    margin-left: auto;
    margin-right:auto;
}

The above gives me the desired effect, but doesn't allow me to position the images absolute. Can anyone suggest a way of centering the images but also allows me to fade one over the other?

Answer

Samec Hadra picture Samec Hadra · Mar 19, 2015

Pushing the element left by 50% of its width and then translating it horizontally by 50% has worked for me.

.element {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
} 

I found the concept in the following link, and then I translated to fit my horizontal align needs: https://gist.github.com/colintoh/62c78414443e758c9991#file-douchebag-vertical-align-css