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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With