Search code examples
htmlcssflexbox

What is the difference between baseline, first baseline, and last baseline in CSS?


The CSS property align-items can be set to baseline, first baseline, and last baseline (CSS Spec). What are the differences between these values?

.flex-container {
  color: white;
  display: flex;
  width: 300px;
  height: 200px;
  background-color: yellow;
}

.flex-item {
  background-color: green;
  width: 50px;
  min-height: 100px;
  margin: 10px;
}

.item1 {
  align-self: flex-start;
}

.item2 {
  align-self: baseline;
}

.item3 {
  align-self: first baseline;
}

.item4 {
  align-self: last baseline;
}
<div class="flex-container">
  <div class="flex-item item1">flex-start</div>
  <div class="flex-item item2">baseline</div>
  <div class="flex-item item3">first baseline</div>
  <div class="flex-item item4">last baseline</div>
</div>


Solution

  • first baseline and baseline are synonyms.

    "First" and "last" refer to the line boxes within the flex items. The best way to understand is with an example:

    section {
      display: flex;
      flex-wrap: wrap;
      position: relative;
    }
    .first {
      align-items: first baseline;
    }
    .last {
      align-items: last baseline;
    }
    div {
      flex: 1;
    }
    div:nth-child(2) {
      font-size: 2.5em;
    }
    
    hr {
      width: 80%;
    }
    
    /* to depict where the relevant baseline is */
    section .baseline-indicator {
      position: absolute;
      border-bottom: 1px solid red;
      width: 100%;
    }
    .first .baseline-indicator {
      top: 36px;
    }
    .last .baseline-indicator {
      top: 173px;
    }
    <section class="first">
      <div>alpha<br>beta<br>gamma</div>
      <div>delta<br>epsilon<br>zeta<br>eta</div>
      <div>iota</div>
      <div class="baseline-indicator"></div>
    </section>
    <hr>
    <section class="last">
      <div>alpha<br>beta<br>gamma</div>
      <div>delta<br>epsilon<br>zeta<br>eta</div>
      <div>iota</div>
      <div class="baseline-indicator"></div>
    </section>

    We can see from the red lines that with first baseline, the baselines of the first text rows (i.e. "alpha", "delta", "iota") are aligned.

    And with last baseline, the baselines of the last text rows (i.e. "gamma", "eta", "iota") are aligned.