skip to Main Content
const myBtn = document.getElementById("btn");
myBtn.addEventListener('click', () => {
    if(myBtn.innerHTML) {
        myBtn.innerHTML = ''
    } else {
        myBtn.innerHTML = 'x'
    }
})
<div style="border: 1px solid red">
  <button id="btn" style="height:50px;width:50px">  </button>
</div>

I am trying to build a tic-tac-toe game as a project. The problem is when I write a button, and on clicking it, adding an ‘x’ or ‘o’ inside it, the layout around it changes. This distorts my layout.

I am not able to understand why this is happening. Is this the expected behavior of HTML?

I have created a small sample for the problem in the code above. Can anyone please point me in the right direction?

2

Answers


  1. document.getElementById("btn").addEventListener('click', () => {
      if(document.getElementById("btn").innerHTML == 'x') {
        document.getElementById("btn").innerHTML= '&nbsp;'
      } else {
        document.getElementById("btn").innerHTML= 'x'
      }
    })
    <div style="border: 1px solid red">
      <button id="btn" style="height:50px;width:50px">&nbsp;</button>
    </div>

    &nbsp;

    Non-breaking Space, the "placeholder" no1, because html doesn’t like empty tags.

    Login or Signup to reply.
  2. You can use vertical-align: middle on buttons to achieve your goal, so when you add ‘x’ or ‘o’ to the button, it will be centered vertically and won’t affect the layout around it. Something like:

    const myBtn = document.getElementById("btn");
    myBtn.addEventListener('click', () => {
        if(myBtn.innerHTML) {
            myBtn.innerHTML = ''
        } else {
            myBtn.innerHTML = 'x'
        }
    })
    <div style="border: 1px solid red">
      <button id="btn" style="width:50px;height:50px;vertical-align: middle"></button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search