How do you vertically align texts in CSS?

Ask a question
5

Hello. I have a div element that contains text. I am trying to align the contents of this div vertically center. Can you, please help me to do that with examples?

Coin iconoffer bounty
add comment

4 Answers

1

It is too simple

div.container {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle 
}
add comment
2

Hi. Please try Flexbox. The Sample is bellow

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      section { 
        display: flex; 
        width: 50%; 
        height: 200px; 
        margin: auto; 
        border-radius: 10px; 
        border: 3px dashed #1c87c9; 
      } 
      p { 
        margin: auto; /* Important */ 
        text-align: center; 
      }
    </style>
  </head>
  <body>
    <section>
      <p> I'm centered with Flexbox!</p>
    </section>
  </body>
</html>
add comment
1

Actually, there are many ways to do that;
-Floater div
-CSS vertical-align Property
-Absolute Positioning and Negative Margin
-CSS Flexbox
-CSS Table Display
-Equal Top and Bottom Padding
-Absolute Positioning and Stretching
-Transform Property

A more versatile approach, which will align text vertically. It works for a single line and multiple lines of text, but requires a fixed height container:

center {
  line-height: 200px;
  height: 200px;
  border: 3px solid green;
  text-align: center;
}

/* If the text has multiple lines, add the following: */
.center p {
  line-height: 1.5;
  display: inline-block;
  vertical-align: middle;
}
add comment
1

You should set the line-height , which should be greater than the height of the image and then set vertical-align: middle on the image.

<div id="parent">
    <img src="image.png" alt="" />
</div>
css
#parent {
    line-height: 200px;
}
#parent img {
    vertical-align: middle;
}
add comment

Your Answer