How to Vertically Align a Text Within a <span> Tag to the Center

Solutions with CSS properties

In the example below, we use a <span> element with a class attribute and then style it with CSS. We set the display to "flex", specify the height, border, and padding properties. Then, we add the white-space property with its "normal" value and the word-break property set to "break-word". Finally, we center the text in our <span> by setting the align-items property to "center".

In order to horizontally align a content inside a div or span to center, you should set the justify-content property to center. Click here to learn more.

Example of vertically centering a text within a <span> with the CSS align-items property:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
   <style>
     .example {
       height: 200px;
       border: solid #CCCCCC 2px;
       padding: 0 10px;
       white-space: normal;
       word-break: break-word;
       display: flex;
       align-items: center;
     }
   </style>
 </head>
 <body>
   <span class="example">
     This is a vertically aligned text.
   </span>
 </body>
</html>

Result

This is a vertically aligned text.

In the next example, to center the text inside a <span>, we use the text-align property. Here, we set the display to “inline-block” and specify the width as well.

Example of vertically centering a text within a <span> with the CSS text-align property:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
   <style>
     span {
       display: inline-block;
       width: 9em;
       text-align: center;
       border: 1px solid green;
       white-space: normal;
       word-break: break-word;
       padding: 60px 0;
     }
   </style>
 </head>
 <body>
   <span>
     This is a vertically aligned text.
   </span>
 </body>
</html>

In our last example, we use the vertical-align property with the "middle" value and specify the line-height, border, and display properties.

This solution may lead to undesired results when the text wraps.

Example of vertically centering a text within a <span> with the CSS vertical-align property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .example {
        line-height: 150px;
        border: 1px solid #000;
        display: inline-block;
        vertical-align: middle;
      }
    </style>
  </head>
  <body>
    <span class="example">
      This is a vertically aligned text.
    </span>
  </body>
</html>