Centering div’s content on a page

Centering a div on a page is easy.  If you don’t know how to do it, a quick google search will turn up tons or answers for it.

Today, I had to stop and think for a few minutes.  I wanted to center a div on a page, but I didn’t know the exact width that the div needed to be.  This proposed a slight problem to me because the contents of my div happened to not fill up the entire div.  So if I just centered the div on the page using margin:auto, there would be a huge whitespace off to the right side.

I guess I could have accomplished this in javascript, but since I wanted to do it in CSS, I did, and thought I would share.

You first need to set a container div to 100%.

<div style=”width:100%”>
Next, you need to get the width of the div contents and reposition the div to 50% of the screen.  We get the div’s contents width by using width:auto.  This can only be used with float: and with position:absolute.
<div style=”float:left; width:auto; position:relative; left:50%;”>
Now we need to backtrack out content div to be 50% less than it’s current position.
<div style=”float:left; position:relative; left:-50%;”>
You final code should look like this:
<div style=”width:100%”>
<div style=”float:left; width:auto; position:relative; left:50%;”>
<div style=”float:left; position:relative; left:-50%;”>
Content Here
</div>
</div>
</div>
A little cumbersome, but it works.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: