Languages

CSS - how to center sibling elements vertically in div?

1 points
Asked by:
AnnLen
9180

I have image and link with text inside a div element.

How can I center all elements inside this div vertically?

Below code will output the the result like this:

As we can see the 'Created by:' span and 'Username' a href element are at the bottom of the line, but I'd like to have them in the middle of the picture, how to make it work?

My code:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div class="my-div">
    <span >Created by:</span>
    <img width: 50px alt="User pic"
      src="https://dirask.com/static/bucket/1596732157426-jm9AdKBDp3--image.png">
    <a href="">Username</a>
  </div>
</body>
</html>

I uploaded mini pic used in this example:

 

1 answer
1 points
Answered by:
AnnLen
9180

Quick solution:

<div class="my-div" style="display: flex; align-items: center;">

We just need to add display: flex; align-items: center; to outer div.

Full working code example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div class="my-div" style="display: flex; align-items: center;">
    <span >Created by:</span>
    <img width: 50px alt="User pic"
      src="https://dirask.com/static/bucket/1596732157426-jm9AdKBDp3--image.png">
    <a href="">Username</a>
  </div>
</body>
</html>

It will produce the result like this:

All elements should be in the middle of the picture :D

0 comments Add comment
Native Advertising
50 000 ad impressions - 449$
­čÜÇ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join