bennofs
bennofs

Reputation: 11963

How to align center of one element with baseline of another in a flexbox

A simple question: how do I align the center of one element with the baseline of another? Here's an example:

span {
  display: flex;
  align-items: center;
}

svg {
  width: 100px;
  height: 100px;
}
<span>
            <svg version="1.1"
                 baseProfile="full"
                 viewBox="0 0 300 300"
                 xmlns="http://www.w3.org/2000/svg">

                <rect x=0 y=0 width="300" height="300" fill="red" />

                <circle cx="150" cy="150" r="80" fill="green" />

                <line x1="0" y1="150" x2="300" y2="150" stroke="black"/>

            </svg>

            <i>Something good text</i>
</span>

I want the center of the svg (marked by the black line) to be aligned with the baseline of the text. Of course, it may be possible to this with hardcoded negative margins or other fixed pixel offsets, but I would like to avoid that.

Upvotes: 2

Views: 591

Answers (1)

Temani Afif
Temani Afif

Reputation: 273086

No need flexbox for this:

svg {
  width: 100px;
  height: 100px;
  vertical-align: middle;
}

i {
  display: inline-block;
  transform: translateY(-0.5ex);
}
<svg version="1.1"
                 baseProfile="full"
                 viewBox="0 0 300 300"
                 xmlns="http://www.w3.org/2000/svg">
     <rect x=0 y=0 width="300" height="300" fill="red" />
     <circle cx="150" cy="150" r="80" fill="green" />
     <line x1="0" y1="150" x2="300" y2="150" stroke="black"/>
</svg>
<i>Something good text</i>

middle

Aligns the middle of the element with the baseline plus half the x-height of the parent. ref

So I rectify the plus half the x-height with a translation using minus half the x-height

Upvotes: 2

Related Questions