Positioning image in div

liunx

Guest
The img "b" should end up in the middle of the screen both vertically and horizontally. Horizontally this works but vertically the html and body expands by double so the img sits far too low on the page. I don't understand why the vertical container doubles in height.

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" xml:lang="en" lang="en">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href=http://www.webdeveloper.com/forum/archive/index.php/"index.css" />
</head>

<body>

<div id="header">
<p>Hello</p>
</div>

<div id="graphic">
<img id="b" src=http://www.webdeveloper.com/forum/archive/index.php/"./images/toast.jpg" alt="hello" />
</div>

</body>
</html>

CSS:

html, body
{
height:100%;
width:100%;
margin:0; padding:0;
}

#graphic
{
width: 100%;
height:100%;
}

#b
{
width:21em;
height:9em;
margin-left: 50%;
margin-top: 50%;
}I think this is the answer I expected. From the W3C spec:

<percentage>
The percentage is calculated with respect to the width of the generated box's containing block. This is true for 'margin-top' and 'margin-bottom', except in the page context, where percentages refer to page box height.You're butting your head against the CSS Box Model (<!-- m --><a class="postlink" href="http://www.w3.org/TR/CSS21/box.html#box-dimensions">http://www.w3.org/TR/CSS21/box.html#box-dimensions</a><!-- m -->) and positioning at the same time. For one, your document is the window width and height, as well as the #graphic DIV. Problem is #graphic is still in the normal document flow, according to your HTML and CSS. The #header is too. So the #graphic is pushed down to make room for #header -- and then #graphic is the same width and height as the document. Your entired document height is the height of the #header plus the height of the #graphic. That's why it's extending down too far. What you really want is either a background image (if the image is purely decorational) or a positioned image (using absolute positioning to make the image its own layer).

If the image is decorational: use a background for the BODY.

If the image relates to the content, use an <img /> tag and position it absolutely to make it its own layer.Well, no. I'm aware that the total height was equal to all that as you said but the image was pushed down much further. At 50% the image was almost off the bottom of the screen. I could tell that was probably around 500px while my browser width was around 1024. That raised my suspicions. Then I ran across the statement above which confirmed what was happening.
 
Back
Top