0

I have 2 divs within a parent div. Each has display set to inline-block;. However they are not vertically aligned. I would expect that either their tops or bottoms are aligned. Why does this occur? and How to get them aligned?

enter image description here

.image {
  display: inline-block;
  border: grey 1px solid;
}

.name {
  display: inline-block;
  margin-left: 4px;
  border: grey 1px solid;
  height: 24px;
  line-height: 24px;
}
<div class=icon>
  <div class=image>
    <img src="https://via.placeholder.com/48" width="24px" height="24px">
  </div>
  <div class=name>Name field</div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
RaelB
  • 3,301
  • 5
  • 35
  • 55
  • I am not displaying this in a modern browser. I am displaying this in a custom control that does not support flex, it only supports standard css and html. – RaelB Aug 30 '22 at 18:34

2 Answers2

3

Both images and text have whitespace allowances for descenders, being inline content. They happen to not be the same size.

A modern solution is flexbox.

.icon {
  display: flex;
  align-items: center; /* or 'start' (top), or 'end' (bottom) */
  background: pink; /* for demo only */
  padding: 8px; /* for demo only */
}

.image {
  border: grey 1px solid;
  font-size: 0; /* one way to eliminate descender space on images */
}

.name {
  margin-left: 4px;
  border: grey 1px solid;
  height: 24px;
  line-height: 24px;
}
<div class=icon>
  <div class=image>
    <img src="https://via.placeholder.com/48" width="24px" height="24px">
  </div>
  <div class=name>Name field</div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 1
    Thanks for the comment about descenders. I found more info here: https://mor10.com/removing-white-space-image-elements-inline-elements-descenders/. I'm not sure if your statement that "They happen to not be the same size" is actually correct. In my case, if I remove the `height` and `line-height` definitions, then the bottom borders of text and image are exactly aligned. But adding a `height` value pushes the bottom border down, instead of dividing the "new" space equally above and below the text... – RaelB Aug 30 '22 at 22:27
-1

You can try this position relative with position absolute check this

.icon {
  position: relative;
}

.image {
  position: absolute;
  top: 0;
  left: 0;
}

.name {
  position: absolute;
  top: 0;
  left: 30px;
  background-color: blue;
  height: 24px;
  line-height: 24px;
}
<div class=icon>
  <div class=image>
    <img src="https://via.placeholder.com/48" width="24px" height="24px">
  </div>
  <div class=name>Name field</div>
</div>
Mohamad
  • 602
  • 2
  • 5
  • 18