Search code examples
htmlcssvertical-alignment

Understand CSS text position


I want to vertically align text relative to a div positions next to it, like the follow: enter image description here

But while try to do it I've notice that the height of the wrapper div that wraps the text and the cube, is a bit higher than it should, as you can see here: https://jsfiddle.net/x7sr9mb1/1/

.table-keys-wrapper {
  display: inline-block;
}

.key-color {
  display: inline-block;
  background: black;
  width: 20px;
  height: 20px;
}
<div class="table-key">
  <div class="table-keys-wrapper">
    <span id="key-sow" class="key-color"></span>
    <span class="key-text">Sowing</span>
  </div>
  <div class="table-keys-wrapper">
    <span id="key-plant" class="key-color"></span>
    <span class="key-text">Planting</span>
  </div>
  <div class="table-keys-wrapper">
    <span id="key-harvest" class="key-color"></span>
    <span class="key-text">Harvesting</span>
  </div>
  <div class="table-keys-wrapper">
    <span id="key-storage" class="key-color"></span>
    <span class="key-text">Storage</span>
  </div>
</div>

The results:

enter image description here

Why the outer div doesn't get the cube's height, as it's height is set to height: auto; (default)

Another question, what is the best way to vertical align the text relatively to the cubes?

Much appreciate the help


Solution

  • inline-blocks elements , just like text, stands on the baseline.

    baseline is the default value to vertical-align.

    reset this value to vertical-align:middle for your inline-block boxes

    .key-color{
      display: inline-block;
      vertical-align:middle;/* reset */
      background: black;
      width: 20px;
      height: 20px;
    }