Steveo
Steveo

Reputation: 2268

A CSS absolute positioning mystery

Consider the webpage below. The <img> is positioned absolutely relative to its parent, and when I load this page on Safari or Firefox, the <img> appears in the top-right, as expected (see first image). However, when the border is removed from from the <div>, for example, by setting border-width: 0, the <img> positions itself absolutely relative to the <p> tag, its sibling! See picture #2. Why is this? What difference should the border make?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<style type="text/css">
body {
    margin: 0;
}
div {
    position: relative;
    left: 0;
    top: 0;
    border: 1px solid red;
}
img {
    position: absolute;
    right: 0;
    top: 0;
}
p {
    margin: 20px;
}
</style>

</head>
<body>
    <div>
        <img src="content/en/flag.png" />
        <p>This is a test</p>
    </div>
</body>
</html>

absolutely relative to div absolutely relative to p

Upvotes: 5

Views: 161

Answers (2)

pzin
pzin

Reputation: 4248

Your image is always at the top-right. It has to do with collapsing margins.

Try to do it with a background color. You will see that your div is moving away from the top of the body a few pixels. If you delete p's margin everything would be fine, or setting p as an inline element or floating it, or even setting an overflow to auto, hidden or scroll to the parent. Another way to fight the collapsed margin is to add a border to the container element. So you really was solving this with that border.

But image is always where it is supposed to be.

Upvotes: 2

Hushme
Hushme

Reputation: 3144

Its really strange indeed but let me try to explain this actually the elements are not float and you are using margin on p tag which the div is taking properly when it has border and failed to implement it when its removed if add float property than the div will also gain its height

add overflow:auto; to div it will fix the problem

Upvotes: 0

Related Questions