SOLVED – How to Center a DIV Using CSS

0
2

Sometimes something you think is going to be really simple in web design can turn out to be a complete nightmare! What's even worse is when you finally find that solution and it was really simple all along. This is exactly the experience I had recently while trying to center a <div> tag horizontally using CSS.

I've seen the question, "How do I center a div horizontally?" asked many times in web design forums and never found anyone who seems to have solved the problem properly. Some come close and others just plain don't work. Well here I believe I have solved the problem fully. Here is the code, I'll explain how it works later:

In the CSS file insert the following code:

#wrapper {

margin: 0 auto;

width: 1000px; / * this is how wide my content is * /

}

#content {

position: relative;

left: 50%;

margin: -500 / * half the width of my content * /

}

Now in your html you need to layout your code something like this:

<html>

<head>

<title> Insert Title

<style type = "text / css" media = "screen"> @ import url (../ includes / layout.css); </style>

</ head>

<body>

<div id = "wrapper">

<div id = "content"> Insert the content you want centered here </div>

</ div>

</ body>

</ html>

So now any content you have put inside the #content div tag will be centred. A couple of things to point out in the CSS are 1) in the #wrapper class you will notice that I have set the width to 1000px, you should change this to suit the width of your content. This leads on to 2) in the #content class you will see that I have set the margin to -500. You should change this to minus half the width of your content.

The way this works is reasonably simple. Let's go through the #content class first. The "left: 50%;" will shift the #content div so that it starts halfway across the browser window. Not much use by itself, but "margin: – [half the width of your content];" then shifts the #content div half the width of your content back towards the left hand side, or in other words centers the div!

This is all well and good but if you resize your browser window you will notice that when your browser window is no longer wider than your content, your content starts to disappear off the left hand side of the screen! This is where the "position: relative;" comes in. If you put the #content div inside another div, in this example the #wrapper div, and position it relative to that div then your #content div won't disappear off the left hand side of the screen. You must however set the #wrapper class div to be the same width as your content: "width: [your content width];". I have also set the margin to "margin: 0 auto;" so that the #wrapper div is placed where I want it.

I hope this helps you with centring you <div> 's and saves you the time and frustration I went through!

Source

Leave a Reply