Click to See Complete Forum and Search --> : Centred Div


Dysan
01-20-2008, 03:05 PM
Hi, Using the following HTML & CSS code, is it possible to vertically and horizontally align the container div?

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="index.css" />
</head>

<body>
<div id="container">

</div>
</body>
</html>


CSS

*
{
FONT-SIZE: 8pt;
FONT-FAMILY: Verdana;
}

body
{
MARGIN: 0px auto;
BACKGROUND: url(BG.bmp) no-repeat;
}

#container
{
WIDTH: 733px;
BORDER: 1px solid rgb(0,0,0);
}

wilku
01-20-2008, 03:51 PM
The way I do it:

text-align: center;
position: absolute;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top:-100px;

reddrum
01-20-2008, 10:43 PM
I have always been irritated with the fact that you can’t just add align=”center” to a div tag. I have wanted to try out this idea for some time, so when I saw your post I thought it a good time. This JS function takes the client’s screen width less the object width divided by 2, which should provide equal distance on each side of the object. I tried it on IE and Firefox it seems to work, although a lot of trouble just to center a div tag.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title></title>
<script language="JavaScript" type="text/javascript">

function center_obj(obj1){
var ref = document.getElementById(obj1);
var sw = screen.width;
var ow = ref.style.width;
var n = ow.substr(0,(ow.length-2));
var goLeft = (sw - n) * 0.5;
ref.style.left = goLeft+'px';
}

</script>
</head>

<body>
<div style="width: 75px; height: 30px; background: #CFDBE4; position: relative; left: 0px;" id="obj1"></div>
<script language="JavaScript" type="text/javascript">

center_obj('obj1');

</script>
</body>

</html>

NogDog
01-21-2008, 03:38 AM
Horizontal centering is easy for fixed-width block elements: just assign margin values of "auto" for the left and right margins.

div#container {
width: 700px;
margin: 0 auto;
}

reddrum
01-21-2008, 12:12 PM
div#container {
width: 700px;
margin: 0 auto;
}




And yet another reason to give up tables!

Weedpacket
01-22-2008, 03:31 AM
And yet another reason to give up Internet Explorer.