View Full Version : Align Divs

01-19-2012, 05:36 PM
How can I align a div so that it always goes into the center of the screen.

01-19-2012, 05:50 PM
Hi there UltimateCoder,

does this help...

<html lang="en">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">

<title>centered element</title>

<style type="text/css">
body {
#container {
border:1px solid #000;


<div id="container">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultricies sollicitudin nisi,
ut molestie felis adipiscing sit amet. Sed auctor vehicula commodo. Nam a nibh neque, vitae
faucibus felis. Vivamus at metus eget eros consequat fringilla. Quisque magna magna, laoreet
eu tempus sit amet, fringilla at tellus. Praesent felis tortor, scelerisque vitae fringilla
non, porttitor et lacus. Ut ut sapien nec quam tincidunt consectetur in nec lacus.
Phasellus porta, dui a elementum egestas, odio sapien rhoncus lorem, vitae bibendum erat sem
eget sapien. Maecenas ut metus ac quam pellentesque lacinia quis sit amet augue. Fusce eu
euismod urna. Nunc volutpat scelerisque tempus. Donec eget arcu et mauris scelerisque
tristique. Donec fringilla mauris dolor, sit amet vulputate lacus. Nulla feugiat mattis nulla
non tincidunt. Nam sit amet dolor eros, a viverra lacus. Nunc quis nisi eget neque tempus
facilisis eu quis sapien.



01-19-2012, 05:58 PM
Aligning DIVS in CSS can sometimes be an issue. One way you could do it is to use the "margin-left" property and set it to a value of like 200px. You can experiment with that to see what the best value is, also I believe you can use % like 25% for that CSS property.

At my employer we have a website for selling Electronic Components and I use the margin properties quite extensively within the website.

Also this css will work independently of whatever coding platform you are using, whether it is ASP.NET or ColdFusion or PHP.

Are you aware of the IE 6 CSS bug? for some reason in IE6 if you use the CSS margin the browser will double the value of the margin if the style has a "float:left;" very annoying. The fix for this is to make sure that the style has a "display:inline;" within it.

01-19-2012, 07:30 PM
Hello UltimateCoder,
Thought I might chip in a bit here...

To center an element you need three things:

a valid DocType
an element with a width
that elements right/left margins set to auto

That takes care of the x axis.
To center on the y takes a little more work. The best way by far is when you know the height of what you are trying to center on the y axis - vertical center (http://nopeople.com/CSS%20tips/vertical%20center%20with%20CSS/page4.html) (view the source to see how it's done)