0

My All the boxes are on same level when I don't add any text but as soon as I add text Two of them start floating I want them to be on same level even after putting text.

  <div class="main-container">
        <div class="container">
            <div class="boxes">s</div>
            <div class="boxes"></div>
            <div class="boxes"></div><br>
            <div class="boxes"></div>
            <div class="boxes"></div>
            <div class="boxes"></div><br>
            <div class="boxes"></div>
            <div class="boxes"></div>
            <div class="boxes"></div>
        </div>
    </div>
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.main-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.boxes {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 2px solid black;
  margin: 4px;
  font-size: 3em;
}

Click to see the Fiddle

1 Answers1

1

To keep all the boxes on same level. set the vertical-align to bottom in boxes class.

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.main-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.boxes {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 2px solid black;
  margin: 4px;
  font-size: 3em;
  vertical-align: bottom;
}
<div class="main-container">
  <div class="container">
    <div class="boxes">S</div>
    <div class="boxes"></div>
    <div class="boxes"></div><br>
    <div class="boxes"></div>
    <div class="boxes">F</div>
    <div class="boxes"></div><br>
    <div class="boxes"></div>
    <div class="boxes"></div>
    <div class="boxes">R</div>
  </div>
</div>

Explanation

This happens because by default the vertical-align is baseline.

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

In case div is empty, its baseline is bottom margin edge and when we add text in div it's baseline becomes the last text line. When you add a character in a div it changes the baseline of that div and aligns with baseline of empty div.

Shikhar Awasthi
  • 1,172
  • 1
  • 3
  • 13