HTML why are these two elements not positioned directly on top of each other?

Viewed 60

I am trying to write some HTML code to overlay another element directly on top of a pre text block.

The problem is, even the most simple example doesn't seem to align correctly...

<div style="position:relative">
<pre style="position:absolute">
hello
</pre>
  <div style="position:absolute">
    world
  </div>
</div>

You can see the output here.

The div element is rendered above the pre element. Why is this happening?

More information on positioning of elements can be found here.

2 Answers

Actually the div element "is" rendered above the pre element. We are just not able to see it. I added a border attribute of css to visualize it because of the "pre margin".

<div style="position:relative">
  <pre style="position:absolute">
hello
</pre>
  <div style="position:absolute; border:1px solid red;">
    world
  </div>
</div>

That said, you can now add some css to shift it a bit and get what you want, like this!!

<div style="position:relative">
  <pre style="position:absolute">
hello
</pre>
  <div style="position:absolute; border:1px solid red; top: 7px">
    world
  </div>
</div>

Hope that helps!! Also it turns out that the pre tag has some default margin at the top. To see that check this out!!

Check this Fiddle

So to remove that, easy, put margin to 0. Fiddle

The pre tag has a margin of margin: 1em 0px; by default so you need to set the margins to zero to override this. Then there is still a small amount of gap after this. This is because of the font. In my example. I have overridden the font-family to inherit the font-family of the parent so the elements are perfectly aligned. Another thing is, the same vice versa effect can be done for font-family for the div tag instead of the pre tag

pre{
margin:0px;
font-family:inherit;
}
<div style="position:relative">
<pre style="position:absolute">
hello
</pre>
  <div style="position:absolute">
    world
  </div>
</div>

Related