0

I have an inline-block element inside a div that I need vertically aligned in the middle. However, the attribute doesn't work as expected and is always a little pushed down. This fiddle demonstrates the problem https://jsfiddle.net/e4spxubf/

I have tried setting the height and line-height of both the child parent elements to the same 14px.

<div style="
    height: 14px;
    line-height: 14px;
    background-color: red;
"><span icon="eye-open" style="
    vertical-align: middle;
    background-color: aquamarine;
    height: 14px;
    width:14px;
    display: inline-block;
"></span></div>

I expect that the blue box will be perfectly vertically centered in the parent.

codeherk
  • 1,609
  • 15
  • 24
  • I added some duplicates that explain how vertical-align works ... TL;DR from them, middle doesn't mean center of the parent element but *the baseline plus half the x-height of the parent* --> you have to identify the baseline and the x-height (ex unit) – Temani Afif Jun 08 '19 at 09:36

1 Answers1

0

The div is aligning itself with the baseline of the span. When you set vertical-align: baseline, you'll find the span now aligns itself with the baseline, too.

Rob
  • 14,746
  • 28
  • 47
  • 65
  • But using `vertical-align: top` means that it will remain anchored to the top even when the height of the parent is increased, I don't want that behavior. Also, why does it align itself with the baseline when I select `vertical-align: middle` rather than `vertical-align: baseline`? – mofovogafa Jun 08 '19 at 02:45
  • @mofovogafa I was correcting my post while you read it. Please check my edit. – Rob Jun 08 '19 at 02:46
  • I think I understand. So what can I do to get `vertical-align` to work as expected here? i.e. the span to perfectly center itself in the parent without making the parent align itself to the child? – mofovogafa Jun 08 '19 at 02:53
  • @mofovogafa It is `line-height` affecting the baseline. If you increase the height of the div, you need to increase the line height the same amount. Assuming I understand what you are trying to do. – Rob Jun 08 '19 at 02:55
  • I used `vertical-align: baseline` as you suggested and tried increasing both the parent's `height` and its `line-height` to 20px. The child refuses to remain vertically centered (i.e 3.5px to the top/bottom). Fiddle: https://jsfiddle.net/e4spxubf/1/ – mofovogafa Jun 08 '19 at 03:09