...

View Full Version : Centering a block element



johnnyb
10-22-2005, 06:07 AM
Hello,

I'm sure this has all been covered before, but it has such generic terms that I couldn't find the answer with a search.

I want to center a <div> element on the page using CSS. I have tried to set the 'text-align' property of <body> to "center" but that doesn't work since a <div> is a block level element as opposed to an inline element.

Does anyone know how to do this?

Thanks in advance.

John

bazz
10-22-2005, 05:08 PM
did you try,

margin : auto auto:

Bazz

harbingerOTV
10-22-2005, 07:24 PM
are you trying to center the div both horizontally and vertically? Is this div the only thing on the page or is it a child of another div?

The easy way would be to contain the div inside a table. i know I know...tables bad, but tables work for this.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>centered divs</title>
<style type="text/css">

table {
width: 100%;
height: 100%;
}

td {
vertical-align: middle;
text-align: center;
}

#box {
width: 200px;
height: 200px;
background-color: #fc6;
margin: auto;
}
</style>
</head>
<body>
<table><tr><td><div id="box"></div></td></tr></table>
</body>
</html>


pretty sure DocType is essential.

as a child:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>centered divs</title>
<style type="text/css">
body {
text-align: center;
}

table {
width: 100%;
height: 100%;
}

td {
vertical-align: middle;
text-align: center;
}

#box {
width: 200px;
height: 200px;
background-color: #fc6;
margin: auto;
}

#container {
width: 600px;
height: 600px;
margin: 0 auto;
border: 1px solid #000;
}

</style>
</head>
<body>
<div id="container">
<table><tr><td><div id="box"></div></td></tr></table>
</div>
</body>
</html>


in columns with a slight fudge to appese IE:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>centered divs</title>
<style type="text/css">
body {
text-align: center;
}

table {
width: 448px;
height: 100%;
float: left;
}

td {
vertical-align: middle;
text-align: center;
}

#box {
width: 200px;
height: 200px;
background-color: #fc6;
margin: auto;
}

#container {
width: 600px;
height: 600px;
margin: 0 auto;
border: 1px solid #000;
}

#left {
width: 150px;
height: 600px;
background-color: #63c;
float: left;
}

</style>
</head>
<body>
<div id="container">
<div id="left"></div>
<table><tr><td><div id="box"></div></td></tr></table>
</div>
</body>
</html>


you can accomplish this with negative margins but this just seems easy enough to do to not worry about the negative margins getting chewed up by old browsers.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum