Legeo
Legeo

Reputation: 792

Overlapping image inside a table

Question: how 2 images can live in the same td ? how can I overlap the first one?

Bug: the images doesn't overlapping, sometimes the character's image is printed next to the tiles images instead to overlap it.

I will link to you the pen of this little program, try to random generate different times to occur in this bug.

penHere

After the first sections of customization a random map will generate the position of the characters.

I investigate over this bug, and i discover that it's not a problem of coordinates ( they are random generated with this function )

function coordinate(){

    let rowCoord= map.length;
    let cellCoord = map[1].length;

    let coord = {
        row: Math.floor(Math.random() * rowCoord),
        cell: Math.floor(Math.random() * cellCoord)
    }

    return coord;  
};

// this function will place the character if the coordinates are ok. Else we have a callback to the same function.

function placeCharAndItem(char){

    let coord = coordinate();
    // with this if you choose a walkable table to spawn, this is random generated
    if(map[coord.row][coord.cell] === 0 ){
        place(coord, char);
    }
    else{
        placeCharAndItem(char);
    }
};

The map is random generated too. It's something like this.

map = [[1,1,1,1,0],
       [1,0,0,0,0],
       [1,0,1,1,1],
       [1,0,0,0,1],
       [1,1,1,0,1]]

and this is the function that let the character image spawn on the right td

function place(coord, char){
  var charImage = $("<img>").attr("src", char.image).addClass('char');
  var row = $($("#tableGame tr")[coord.row]);
  var cell = $($("td", row)[coord.cell]);
  cell.append(charImage);
};

Thanks :)

Upvotes: 1

Views: 1177

Answers (1)

Nina Lisitsinskaya
Nina Lisitsinskaya

Reputation: 1818

If you just put two images in a table cell, they will be displayed one after the other by default, this is just how the HTML works.

To make overlap of two images you can explicitly set position of the second image relative to it's parent table cell. You can do it with CSS:

  • Apply position: relative; to the parent td;
  • Apply:

    position: absolute;
    top: 0;
    left: 0;
    

    to the second image (and all next images in the same cell, if you will have more).

Keep in mind that second image now will be out of the standard HTML flow, it will no longer affect the cell size, it will overlap anything. You may need to explicitly set the cell size.

Also you can set this styles dynamically with the JQuery:

// Get your table cell and image somehow.
const $cell = $(...);
const $image = $(...);

$cell.css('position', 'relative');
$image.css({
    position: 'absolute',
    top: 0,
    left: 0,
});

Or with a plain JS:

const cell = document.querySelector(...);
const image = document.querySelector(...);

cell.style.position = 'relative';
image.style.position = 'absolute';
image.style.top = 0;
image.style.left = 0;

Upvotes: 1

Related Questions