javascripthtmlcsspositioning

Why are the top: and left: properties inconsistent in my HTML


In my HTML page I have a bunch of pictureframe images I'm trying to line up on a shelf image, I'm trying to complete this by generating top: and left: in px the position of each image with javascript. Each img element is identical with the exception of its ID and its top: and left: position, but for some weird reason left:60px will be a different distance from the left of one element to another. The image provided demonstrates this.

Here is my css for the shelf div they are contained in. Each of the img elements have position relative

#theShelf {
    background-image: url(sprites/shelf2.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    height: 1920px;
    width: 1080px; 
    margin: 0 auto;
  }

I was expecting an element with the same top:px and left:px properties in the same div, with the same dimensions and properties to be in the same place. But it seems many of these elements have inconsistent positions to their numeric values. I have tried changing the position: type of each element to everything I can think of and nothing seems to work.

enter image description here


Solution

  • position: relative means "Work out where this element would be if it wasn't positioned, then move it from that location".

    If you have two <img> elements next to each other without positioning then the browser will render them next to each other (i.e. not overlapping on the same spot).

    To use your approach you should be looking at setting position: relative on a parent element to establish a containing block and then using position: absolute to lay out the individual images within it.

    You might be better off not using positioning and switching to grid instead.