Easy way to center variable width divs in CSS

Talon picture Talon · Sep 1, 2011 · Viewed 20.6k times · Source

I'm trying to center a Div that will have varying width's (based on content of a website).

I read about a relative positioning technique here:

http://www.tightcss.com/centering/center_variable_width.htm

But I thought there has to be an easier way to do it?

Answer

Joe Landsman picture Joe Landsman · Sep 1, 2011

That's a pretty solid method that should work well in most browsers. It's not really that complex when you break it down. Here's a basic example:

<style type="text/css">
#hideoverflow { overflow: hidden; }
#outer { position: relative; left: 50%; float: left; }
#inner { position: relative; left: -50%; float: left; }
</style>

<div id="hideoverflow">
    <div id="outer">
        <div id="inner">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id velit vel  augue fringilla rhoncus at et odio. Suspendisse potenti. Aliquam justo  libero, commodo ut iaculis in, placerat vel purus.
        </div>
    </div>
</div>