Search code examples
cssvertical-alignmentbaseline

Aligning div to baseline of the first line of another div?


I've got two divs and would like to align their baselines. However, one of the divs has more than one line of text and some embedded content, and while I'd like to align them to the top baselines, the browser seems to align to the bottom one.

I've built a JSFiddle here to illustrate, with the following HTML:

<div style='display:inline-block;'>NOTE:</div>
<div style='display:inline-block; width:200px;'>
    Here's <div class='embedded'></div> an embedded div and more text
</div>

and CSS:

.embedded {
    width:40px;
    height:40px;
    display:inline-block;
    vertical-align:-15px;
    border:1px solid black;
}

What I'd like is this:

Images aligned to bottom baseline

What I get is this:

Images aligned to top baseline

A pure-CSS solution would be nice, but I'm not against using JavaScript here either. Any help would be greatly appreciated!


Solution

  • You can do it quite simply with a wrapping div and a bit of flex box.

    .wrapper {
      display: flex;
      align-items: baseline;
    }
    
    .note {
      margin-right: 1ch;
    }
    
    .embedded {
        width: 40px;
        height: 40px;
        display: inline-block;
        vertical-align: -15px;
        border: 1px solid black;
    }
    <div class="wrapper">
      <div class="note" style='display:inline-block;'>NOTE:</div>
      <div style='display:inline-block; width:200px;'>
          Here's <div class='embedded'></div> an embedded div and more text
      </div>  
    </div>