Languages

CSS - how to center elements vertically in div?

1 points
Asked by:
AnnLen
1819

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 answers
1 points
Answered by:
AnnLen
1819

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.