I have the following code:
<!DOCTYPE html>
<html>
<head>
<style>
img
{
position:absolute;
right:50px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<img src="logocss.gif" width="95" height="84" />
</body>
</html>
from http://www.w3schools.com/cssref/tryit.asp?filename=trycss_position_right
If I change the style of h1 to: h1 { position:absolute; right:50px; } then both the h1 and img overlaps.
Now I didn't mention the top position for img or h1. So in the first case when h1 didn't have any style, the img left h1 alone and occupy the next available space after the h1 and was aligned to the right side (50 px apart). But when I mentioned h1 to be 50px apart (with absolute positioning), both the img and h1 overlapped. Now as I didn't mention the top position then why is not img leaving h1 alone and follow it (instead of overlapping it)? I understand that we are using absolute positioning which leaves top position ambiguously specified so why is it automatically assuming that the img has to occupy the top:0 position? If h1 occupies top:0 position then it is fine because it is the first element. But img should respect the space of h1.
Thanks in advance for help.
If position: absolute; or position: fixed; - the right property sets the right edge of an element to a unit to the right of the right edge of its nearest positioned ancestor. If position: relative; - the right property sets the right edge of an element to a unit to the left/right of its normal position.
if a div is fixed or absolute you can use right: 0; to get the div to the right.
This is because position:absolute
removes the element from the flow of the document - they don't stack anymore because they are position absolutely.
I think a better way to do this would be:
h1, img{
float:right;
margin-right:50px;
clear:both;
}
jsfiddle: http://jsfiddle.net/R7bXZ/
Even better way for you:
Just give the h1 text-align:right;
.
jsfiddle: http://jsfiddle.net/KvMLb/2/
yeah, you could also just change the top
tag in the css like so:
img
{
position:absolute;
right:50px;
top:100px;
}
h1
{
position:absolute;
right:50px;
top:75px;
}
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