Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css absolute positioning with right alignment

Tags:

css

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.

like image 446
Md. Reazul Karim Avatar asked Mar 14 '13 18:03

Md. Reazul Karim


People also ask

How do you set a position to the right in CSS?

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.

How do I force a div to the right?

if a div is fixed or absolute you can use right: 0; to get the div to the right.


2 Answers

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/

like image 93
Bill Avatar answered Sep 19 '22 19:09

Bill


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;
 }
like image 35
Mike Avatar answered Sep 18 '22 19:09

Mike