How to do Vertical alignment of an image inside text in CSS

Vertical alignment of an image inside text can be a tricky task in CSS, but with a little bit of knowledge and the right techniques, it can be done easily.

In this CSS tutorial, we will explore different methods for achieving vertical alignment of an image inside text using CSS.


Using the Vertical-Align Property

The vertical-align property is used to align an element vertically with respect to its parent element.

This property can be used to align an image inside text by setting the vertical-align property of the image to middle.

img {
  vertical-align: middle;
}

This will align the image vertically in the middle of the text.

However, this method only works if the image and the text are in the same line.

Using the Line-Height Property

Another method for achieving vertical alignment of an image inside text is by using the line-height property.

This property is used to specify the height of a line of text.

By setting the line-height property of the parent element to the same value as the height of the image, the image will be aligned vertically in the middle of the text.

p {
  line-height: 50px;
}

img {
  height: 50px;
}

This method works even if the image and the text are not in the same line.

Using the Flexbox

A third method for achieving vertical alignment of an image inside text is by using flexbox.

Flexbox is a layout module in CSS that makes it easy to align elements horizontally and vertically.

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

This will align all the children elements inside the parent container to the center vertically.

Using Grid

The last method is using grid, which is also a layout module in CSS.

It allows us to create a grid of rows and columns and place elements inside the cells.

grid-container {
  display: grid;
  align-items: center;
}

This will align all the children elements inside the grid container to the center vertically.

In conclusion, there are several ways to achieve vertical alignment of an image inside text using CSS.

The vertical-align property, line-height property, flexbox and grid are all effective methods for aligning an image vertically inside text.

With a little bit of knowledge and the right techniques, you can easily align an image inside text using CSS.