Search code examples
htmlcssflexboxvertical-alignment

How to align blocks inside text verticaly


How to vertically align center .sub-block-2 element (like .sub-block-1) ? .sub-block-1 should be display=flex .sub-block-2 should be display=inline-flex Behavior should be the same as now except .sub-block-1 and .sub-block-2 should be vertically centered

<div class="wrapper">
  <div class='holder'>
  Some text
    <div class="block">
      <div class="sub-block-1"></div>
    </div>
    <div class="block">
      <div class="sub-block-2"></div>
    </div>
    dsdfsd sdfsdf dsfsdfsdf sdfsdfsdf sdfsdf sdfsdf
  </div>
</div>
.wrapper {
  width: 300px;
}

.holder {
  line-height: 30px;
}

.block {
  display: inline-block;
  vertical-align: middle;
  overflow: hidden;
}

.sub-block-1 {
  display: flex;
  background: #000;
  height: 20px;
  width: 60px;
}

.sub-block-2 {
  display: inline-flex;
  background: #000;
  height: 20px;
  width: 100px;
}

codepen https://codepen.io/ruvi/pen/yLaryJq


Solution

  • inline elements are a little funky with line height. (thread on how line-height affects inline elements)

    Adding line-height: 0; to .block will align both sub-block1 and sub-block2 vertically, although if there's any text inside .block, there will be no extra space between lines.

    .block {
      display: inline-block;
      vertical-align: middle;
      overflow: hidden;
      line-height: 0;
    }