Align flex-box items to baseline of last text line in a block
Asked Answered
A

3

17

I am trying to achive the last example on the following image, using flex-box.

enter image description here

From what I see, the align-items: baseline; property works great when the blocks only have 1 line.

The property align-items: flex-end; creates some issues mainly because the left and right items have different font-sizes and line-heights. Although the edges of the items are aligned, the white space created by the font size and line-height differences looks really bad when the item has no borders.

I'm trying to find a good all-around solution without any JS.

Thanks in advance.

Anglophile answered 25/8, 2015 at 16:35 Comment(0)
D
26

You can wrap the contents of the flex items inside inline-block wrappers:

.flex {
  display: flex;
  align-items: baseline;
}
.inline-block {
  display: inline-block;
}

.item { border: 1px solid red; }
.item:first-child { font-size: 200%; }
.flex::after { content: ''; position: absolute; left: 0; right: 0; border-top: 1px solid blue; }
<div class="flex">
  <div class="item">
    <div class="inline-block">Lorem<br />Ipsum<br />Dolor</div>
  </div>
  <div class="item">
    <div class="inline-block">Foo bar</div>
  </div>
</div>

That will work because, according to CSS 2.1,

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.

Dygert answered 26/8, 2015 at 23:3 Comment(1)
it seems to be working on chrome & edge but not in firefox. Firefox works when inline-block is applied directly to parent <div> elements- in your snipped - class item. Any idea why is it so? The code that works on FF jsfiddle.net/realgs/1fahdw0o . For FF you can also specify last baseline instead of baseline.Rawdan
T
8

At the time of writing the CSS box model alignment working draft proposes a ‘first’ and ‘last’ value to be added to ‘align-items’. The would allow:

align-items: last baseline

Current it only appears to be supported by Firefox so is one for the future.

https://developer.mozilla.org/en-US/docs/Web/CSS/align-items

Tomokotomorrow answered 11/9, 2017 at 10:15 Comment(0)
S
2

https://web.dev/last-baseline/

Last baseline now works across major browsers!

Spaceship answered 24/5, 2023 at 5:58 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Trainer
AI to the rescue once again... The Bot can't understand your answer in context with the other answers. This is clearly an update from Ric's answer. Move along, bot.Shupe

© 2022 - 2024 — McMap. All rights reserved.