1

<style>
  #main {
    width: 110px;
    height: 110px;
  }

  #main div {
    width:50px;
    height: 50px;
    border: 1px solid black;
    display: inline-block;
  }
</style>

<div id='main'>
  <div>x</div>
  <div>x</div>
  <div>x</div>
  <div></div>
</div>

I have a grid of divs set up just a like a checker board. The divs are either empty, or have a single unicode character inside of them.

When a character is removed from or added to the div, the spacing around the div is affected. (see snippet)

How can I stop this behavior? I would like for the content inside of the div to not affect the positioning or spacing around the div.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Evan Payne
  • 131
  • 1
  • 9
  • you could add   to the div where you don't have an input. Flex is a better way to go although that doesn't answer the question as to why this happens. perhaps someone else has an answer – DCR Oct 24 '21 at 20:48
  • again, none of the answers explain why the behavior is happening – DCR Oct 24 '21 at 20:50

4 Answers4

2

Don't use the display:inline-block, try with display:flex on the outer div. Basic concepts of flexbox

Nicola Revelant
  • 102
  • 1
  • 3
2

you can fix your code by adding vertical-align:top to your inner 4 divs

DCR
  • 14,737
  • 12
  • 52
  • 115
0

This issue occurs because of the way that vertical-align is calculated. When no vertical-align is set, the default is baseline. However, when there is no text, baseline is calculated differently. See this answer.

Using FlexBox, as suggested by most of the other answers would obviously avoid this issue.

If you want to avoid FlexBox, probably the best option is to just set vertical-align explicitly, as suggested in DCR's answer.

Another method would be to wrap the inner text in a <span> and add position: absolute. This way, all the boxes effectively have the same size content, and the discrepancy is resolved. Here's an example:

<style>
#main {
  width: 110px;
  height: 110px;
}

#main div {
  position:relative;
  width:50px;
  height: 50px;
  border: 1px solid black;
  display: inline-block;
}

#main div span {
  position: absolute
}
</style>

<div id='main'>
  <div><span>x</span></div>
  <div><span>x</span></div>
  <div><span>x</span></div>
  <div><span></span></div>
</div>
Jacob Lockard
  • 1,195
  • 9
  • 24
-1

Like Nicola Revelant said in their answer, you can use something like flexbox to make this work. Here's an example:

    <style>
      #main {
        width: 110px;
        height: 110px;
        display: flex;
      }

      #main div {
        display: flex;
        flex-direction: column;
      }
      
      #main div div {
        width: 50px;
        height: 50px;
        border: solid 1px black;
      }
    </style>

    <div id='main'>
      <div class="row1">
        <div>x</div>
        <div>x</div>
      </div>
      <div class="row2">
        <div></div>
        <div></div>
      </div>
    </div>
charlie-map
  • 556
  • 5
  • 17