Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Block Positon changes after changing innerHTML

I am trying to make a X-O game
so html is this:

    const blocks = document.querySelectorAll(".block")
    let turn =  "X"
    for (let i = 0; i < blocks.length; i++) {
        blocks[i].addEventListener("click", function () {
            if (this.innerHTML == "") {
                this.innerHTML = turn
            }}
        )}
    .block {
        width: 100px;
        height: 100px;
        border: 1px solid black;
        text-align: center;
        line-height: 100px;
        font-size: 50px;
        font-weight: bold;
        cursor: pointer;
        padding: 0;
        display: inline-block;
}
    #game{
        max-width: 400px;
        max-height: 400px;
}
<div id="game">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
</div>

And every thing is OK.
But when I press a block it’s position changes a little bit:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I have a slightly different solution using rows and column structure and flex.

Divide the structure into a tabular structure (ex: row, column). Try using display:flex to display the boxes in the same line.

const blocks = document.querySelectorAll(".col");
let turn =  "X";
for (let i = 0; i < blocks.length; i++) {
    blocks[i].addEventListener("click", function () {
        if (this.innerHTML == "") {
            this.innerHTML = turn;
        }
    });
 }
.row{
    display: flex;
}
.col {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    text-align: center;
    line-height: 100px;
    font-size: 50px;
    font-weight: bold;
    cursor: pointer;
    padding: 0;
}
#game {
    max-width: 400px;
    max-height: 400px;
}
<div id="game">
  <div class="row">
    <div class="col"></div>
    <div class="col"></div>
    <div class="col"></div>
  </div>
  <div class="row">
    <div class="col"></div>
    <div class="col"></div>
    <div class="col"></div>
  </div>
  <div class="row">
    <div class="col"></div>
    <div class="col"></div>
    <div class="col"></div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading