tags:

views:

352

answers:

4

I would like to have the text My homepage in the middle of the box I made. I saw an example on a web site but this does not work properly, as the text is on the left. How can I fix the code?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/1998/REC-html40-19980424/strict.dtd"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
My homepage
</title>
<style type="text/css">
body {
  background-color: #d2b48c;
  margin-left: 20%; 
  margin-right: 20%;
  border: 1px dotted gray;
  padding: 10px 10px 10px 10px;
  font-family: sans-serif;
}
</style>
</head>
<body>
<div style="width: ???px; position: relative; margin-top: 0px; margin-left: auto; margin-right: auto;">
<h1 id="begin"> My homepage </h1>
</div>
+2  A: 

You see also: Block-level and inline elements

HTML

<div id="container">
  <h1>My homepage</h1>
</div>

CSS

#container h1 {
    text-align: center;
}

I also recommend reading: Descendant selectors, Child selectors and Adjacent sibling selectors

ranonE
The outer div is not required, as `<h1>` is a block level element itself
Rowland Shaw
@Rowland, but that is how the original code was...
peirix
The point is that that `<div>` is not needed though (and `#begin {...}` would work just as well, and highlight that the `<div>` is not used.)
Rowland Shaw
+1  A: 

One simple line of CSS:

#container > h1 { text-align: center; }
peirix
A: 

If you want vertical and horizontal centering you need to use display: table-cell and vertical-align: middle as well as margin: auto;

CSS

#outer {height: 100%; overflow: hidden; position: relative; width: 80%; margin: auto;}
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;}
#middle[id] {display: table-cell; vertical-align: middle; align: center; position: static;}
#inner {position: relative; top: -50%; text-align: center;}

HTML

<div id="outer">
   <div id="middle">
      <div id="inner">
         <h1>My Homepage</h1>
      </div>
   </div>
</div>
beggs
I must say that is the worst vertical centering technique I have ever seen..
peirix
"worst" is a bit strong... I admit it's old (in fact it looks like it does not work in IE7: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html)...
beggs
beggs
A: 

<h1> is a block level element, so you can simply style it with text-align in your CSS:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/1998/REC-html40-19980424/strict.dtd"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
My homepage
</title>
<style type="text/css">
body {
  background-color: #d2b48c;
  margin-left: 20%; 
  margin-right: 20%;
  border: 1px dotted gray;
  padding: 10px 10px 10px 10px;
  font-family: sans-serif;
}
h1 {
  text-align: center;
}
</style>
</head>
<body>
<h1 id="begin"> My homepage </h1>
</body>
</html>
Rowland Shaw