Relative or Absolute position? I made that mistake

Learning the important lesson of child/parent element realities

This brief article is about the problems I faced getting <span/> containers to sit on top of a <div/> container in the same place regardless of screen size, aspect ratio, or orientation. It was a beginner's problem, but I hope it helps somebody in the same position.

The problem

The idea was to create clickable areas on photos of garden beds at my local community garden (I volunteer there doing the IT) so people could click on the plants and explore the beds. The problem was keeping the clickable areas, which had to be separate elements, in the same place on the photo regardless of what the screen was doing.

I used <span/> elements with red borders for the clickable areas and placed them on top of a <div/> element (which was their parent element as well) with the photo as a background image. I made the <span/> elements’ CSS to be position: relative. After all, I wanted them to be relative to the screen, not in an absolute position, right?

The endless rewrites

Then came the rewriting of JavaScript, trying to figure out an algorithm that would keep the span elements in the same place. I eventually did come up with one that would keep them in the same place no matter the screen size – as long as the aspect ratio of the screen stayed the same. No good, because screens come in all different sizes, and on mobile devices, the screen aspect ratio changes dramatically when the screen orientation is changed.

I fiddled endlessly with the JavaScript and CSS until one kind person said to me: why don’t you just make the <span/> elements absolute in their position?

The solution!

I had been so hung up on the fact that the <span/> elements had to be relative to the screen size that I forgot that child elements were positioned according to their parent element; in this case, the <div/> with the photo. If I made the <div/> relative in its position (as its parent element was the body of the page) but made the <span/> elements absolute in their position on the <div/>, they were never going to move no matter what the screen did. Of course, idiot!

So the problem was solved and the day was saved.

This was a very silly oversight by me, but shows how we can get so focused on an erroneous fact that the reality of how things work can pass us by. I hope my mistake prevents you from making a similar one!

For those of you who would like to see the website, here it is. I really should update it now we’re into Summer

Seed Garden Bed Tour