Absolute css positioning with proper alignment

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 h1 and img overlap.

Now I have not mentioned the top position for img or h1. Thus, in the first case, when h1 had no style, img left h1 alone and took the next available space after h1 and was aligned on the right side (50 px separately). But when I mentioned that h1 will be split into 50 pixels (with absolute positioning), both img and h1 overlap. Now that I have not mentioned the top position, why not leave img, leaving h1 alone and follow it (instead of overlapping it)? I understand that we use absolute positioning, which leaves the top position ambiguous, so why does it automatically assume that img should occupy the top position: 0? If h1 is in the top position: 0, then this is normal, because it is the first element. But img must respect the space h1.

Thanks in advance for your help.

+4
source share
4 answers

This is due to the fact that position:absolute removes the element from the document stream - they no longer add up because they are absolutely positioned.

I think the best way to do this is:

 h1, img{ float:right; margin-right:50px; clear:both; } 

jsfiddle: http://jsfiddle.net/R7bXZ/

An even better way for you:

Just give h1 text-align:right; .

jsfiddle: http://jsfiddle.net/KvMLb/2/

+6
source

Yes, you can also just change the top tag in css as follows:

  img { position:absolute; right:50px; top:100px; } h1 { position:absolute; right:50px; top:75px; } 
+2
source

Read here about absolute positioning: http://www.w3.org/wiki/CSS_absolute_and_fixed_positioning

When using absolute positioning, the element to which you apply it, in terms of lamellas, is disconnected from the page and the rest of the elements. In fact, this element behaves on its own, using the influence of 0 from another. From what I read, you need a position: absolute img, to determine where h1 is and avoid it. It is simply not possible using the position: absolute, it is not in itself intended for this.

How do you want them to actually display, so I can help achieve this without using the position: absolute?

0
source

The reason img occupies the top: 0 position is because by specifying h1 as position: absolute , you take it out of the page stream. img tries to calculate its position and does not see h1 there. There is no great way using only position: absolute , although this JSFiddle may work for you .

0
source

Source: https://habr.com/ru/post/1469332/


All Articles