Home > Back-end >  Centering multiple images in a <tr> element
Centering multiple images in a <tr> element

Time:11-07

So I'm building this app which is an implementation of the game "Mancala". In a position of the board there can be "seeds" (game's piece) which I chose to represent as images.

In the initial setup of the game, there are N seeds in each position of the board. I represent this as N equal images ("seed.png") printed randomly in the respective position.

I want images to overlap, so even when N is a big number, they will all fit in the position ("see image nrº1"). What I accomplished so far is a random distribution with little to none overlapping and some "seeds" are getting out of the circle.

This is the code I have, built in JavaScript:

function init_board() {
    const board = document.getElementById("board");
    
    for(let i = 0; i < 2; i  ) {
    const tr = board.insertRow();
    if(i == 0) {
        tr.insertCell().setAttribute("rowSpan", "2");
    }

    for(let j = 0; j < 6; j  ) {
        var x = tr.insertCell();
        for(let k = 0; k < 20; k  ) {
        var img = document.createElement("img");
        img.src = "images/seed.png";
        img.height = "10";
        img.width = "10";
        img.style.position = "relative";
        
        img.style.left = Math.floor(Math.random() * 7)   "px";
        img.style.top = -7   Math.floor(Math.random() * 14)   "px";
        
        x.appendChild(img);
        }
    }
    
    if(i == 0) {
        tr.insertCell().setAttribute("rowSpan", "2");
    }
}

With the following formatting:

#board {
    margin-left: auto;
    margin-right: auto;
    position: relative;
    top: 30%;
}

td {
    width: 75px;
    height: 75px;
    border: 3px solid darkred;
    border-radius: 40px;
    background: antiquewhite;
}

table {
    border: 5px solid darkred;
    border-radius: 20px;
    background: burlywood;
}

Image Nrº1 N=20: https://imgur.com/a/7aNVsUb, Image Nrº2 where N=30 and the seeds change the size of the circle: https://imgur.com/a/2iHXwyd

Thank you in advance!

CodePudding user response:

To apply width and height correctly to td tag, you need to make it an inline-block element.

td:not([rowspan="2"]) {
  display: inline-block;
}

Your pen updated (with seeds=30): CodePen

  • Related