0

I have an icon within a div, positioned vertically using absolute positioning. The div is 39px tall, and the icon is 10px tall:

Image with highly apparent labels

I want this icon vertically centered within the div. My inspector (on Chrome) says that the icon is 14.5px away from the top:

Did I really need to screenshot text?

which would mean the icon should be perfectly, vertically centered within the div. However, it does not look that way. So I measured it. The div is indeed 39px tall and the icon is 10px tall, however... my eyeballs were correct about the image not being centered: the space above the icon is 16px, and the space below is 13px:

What the H! Have the correct space already!

Why is the space above the icon not 14.5px like Chrome says it is and like my code says it will be? Where is the disconnect?

P.S. - I can understand 15px spacing on top and 14px spacing below due to rounding issues, but having a difference of 1.5px gets rid of that theory.

P.P.S - here is an example that more or less reproduces the issue: https://jsfiddle.net/0shzub2t/

P.P.P.S - and here is an example that is a deviation from my code for easier visualization: I think it shows the issue because in the example, I should have the top edge of the image right on the bottom edge of the div but the image is several pixels higher than it should be... https://jsfiddle.net/0shzub2t/1/

Johannes
  • 64,305
  • 18
  • 73
  • 130
JCollier
  • 1,102
  • 2
  • 19
  • 31
  • 1
    Could you supply the offending code? – EGC Oct 16 '19 at 23:22
  • 1
    I just tested this in a plain `
    ` with a single ``. The problem was [*not present*](https://jsfiddle.net/t697d0u4/). Please ensure you have provided a [**minimal, complete, and verifiable example**](http://stackoverflow.com/help/mcve) of the code -- in doing so you'll almost certainly identify the problem.
    – Obsidian Age Oct 16 '19 at 23:23
  • The code is spread out all over the place so it will take me a while to get the relevant stuff. Also, your example uses ```margin-top``` instead of ```top``` like mine does. In your example, get rid of ```margin-top``` from your ```.container``` section and change ```margin-top``` to ```top``` in your ```img``` section. That reproduces it. – JCollier Oct 16 '19 at 23:31
  • I've edited my answer to have links to examples of the error reproduced. – JCollier Oct 16 '19 at 23:45

1 Answers1

4

You should add position: relative; to the .container element, otherwise the absolute position of the image will not relate to its parent .container, but to the next "higher" element which has position: relative, or – if there is no such element – to the root element, which is html. And html in most browsers has a default margin setting, so your centered positioning is off by that margin setting.

But as I wrote: just add position: relative; to .container

Johannes
  • 64,305
  • 18
  • 73
  • 130