How do I vertically center text with CSS?

Irakli Lekishvili Source

I have a div element which contains text, and I want to align the contents of this div vertically center.

Here is my div style:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

What is the best way to do this?

htmlcssvertical-alignment

Answers

answered 7 years ago Michiel van Oosterhout #1

You can try this basic approach:

div {
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 2px dashed #f69c55;
}
<div>
  Hello World!
</div>

It only works for a single line of text though, because we set the line's height to the same height as the containing box element.


A more versatile approach

This is another way to align text vertically. This solution will work for a single line and multiple lines of text, but it still requires a fixed height container:

div {
  height: 200px;
  line-height: 200px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span>
</div>

The CSS just sizes the <div>, vertically center aligns the <span> by setting the <div>'s line-height equal to its height, and makes the <span> an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the <span>, so its contents will flow naturally inside the block.


Simulating table display

And here is another option, which may not work on older browsers that don't support display: table and display: table-cell (basically just Internet Explorer 7). Using CSS we simulate table behavior (since tables support vertical alignment), and the HTML is the same as the second example:

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>


Using absolute positioning

This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article in Smashing Magazine, Absolute Horizontal And Vertical Centering In CSS.

answered 7 years ago Ariful Islam #2

You can easily do this by adding the following piece of CSS code:

display: table-cell;
vertical-align: middle;

That means your CSS finally looks like:

#box {
  height: 90px;
  width: 270px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  margin-top: 20px;
  margin-left: 5px;
  display: table-cell;
  vertical-align: middle;
}
<div id="box">
  Some text
</div>

answered 5 years ago user #3

For a single line of text (or a single character) you can use this technique:

It can be used when #box has non-fixed, relative height in %.

<div id="box"></div>

#box::before {
    display: block;
    content: "";
    height: 50%;
}

#box::after {
    vertical-align: top;
    line-height: 0;
    content: "TextContent";
}

See live demo at JsBin (easier to edit CSS) or JsFiddle (easier to change height of result frame).

If you want to place inner text in HTML, not in CSS, then you need to wrap text content in additional inline element and edit #box::after to match it. (And, of course, content: property should be removed.)
For example,
<div id="box"><span>TextContent</span></div>
In this case #box::after should be replaced to #box span.

For IE8 support you must replace :: with :.

answered 5 years ago Danield #4

Another way (not mentioned here yet) is with Flexbox.

Just add the following code to the container element:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Flexbox demo 1

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 24px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
  justify-content: center;
  /* align horizontal */
  align-items: center;
  /* align vertical */
}
<div class="box">
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
</div>

Alternatively, instead of aligning the content via the container, flexbox can also center the a flex item with an auto margin when there is only one flex-item in the flex container (like the example given in the question above).

So to center the flex item both horizontally and vertically just set it with margin:auto

Flexbox Demo 2

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 24px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
}
.box span {
  margin: auto;
}
<div class="box">
  <span>margin:auto on a flex item centers it both horizontally and vertically</span> 
</div>

NB: All the above applies to centering items while laying them out in horizontal rows. This is also the default behavior, because by default the value for flex-direction is row. If, however flex-items need to be laid out in vertical columns, then flex-direction: column should be set on the container to set the main-axis as column and additionally the justify-content and align-items properties now work the other way around with justify-content: center centering vertically and align-items: center centering horizontally)

flex-direction: column demo

.box {
  height: 150px;
  width: 400px;
  background: #000;
  font-size: 18px;
  font-style: oblique;
  color: #FFF;
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* vertically aligns items */
  align-items: center;
  /* horizontally aligns items */
}
p {
  margin: 5px;
  }
<div class="box">
  <p>
    When flex-direction is column...
  </p>
  <p>
    "justify-content: center" - vertically aligns
  </p>
  <p>
    "align-items: center" - horizontally aligns
  </p>
</div>

A good place to start with Flexbox to see some of it's features and get syntax for maximum browser support is flexyboxes

Also, browser support nowadays is very good: caniuse

For cross-browser compatibility for display: flex and align-items, you can use the following:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

answered 5 years ago bortunac #5

The simple and versatile way is (as michielvoo table approach):

[ctrv]{
    display:table !important;
}

[ctrv] > *{ /* adressing direct discendents */
      display:table-cell;
      vertical-align: middle;
      // text-align: center; /* optional */
}

Using this attribute (or a equivalent class) on a parent tag works even for many childs to align:

<parent ctrv>  <ch1/>  <ch2/>   </parent>

answered 4 years ago ankitd #6

All credit goes to this link owner @Sebastian Ekström Link; please go through this. See it in action codepen. By reading the above article I also created a demo fiddle.

With just three lines of CSS (excluding vendor prefixes) we can do it with the help of a transform: translateY vertically centers whatever we want, even if we don’t know its height.

The CSS property transform is usually used for rotating and scaling elements, but with its translateY function we can now vertically align elements. Usually this must be done with absolute positioning or setting line-heights, but these require you to either know the height of the element or only works on single-line text, etc.

So, to do this we write:

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
} 

That’s all you need. It is a similar technique to the absolute-position method, but with the upside that we don’t have to set any height on the element or position-property on the parent. It works straight out of the box, even in Internet Explorer 9!

To make it even more simple, we can write it as a mixin with its vendor prefixes.

answered 4 years ago Jürg #7

Flexible approach

div {
  width: 250px;
  min-height: 50px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #123456;
  margin-bottom:5px;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
<div>
  <span>Lorem ipsum dolor sit amet.</span>
</div>
<div>

answered 4 years ago Sam Alexander #8

A better, easier, responsive approach is to set margin-top in CSS to around 45%:

margin-top: 45%;

You might have to play with that number, but it will be in the center of the surrounding div.

answered 4 years ago Eseirt #9

Another way:

Don't set the height attribute of the div, but instead use padding: to achieve the effect. Similarly to line-height, it only works if you have one line of text. Although this way, if you have more content, the text will still be centered, but the div itself will be slightly larger.

So instead of going with:

div {
  height:120px;
  line-height: 120px;
}

You can say:

div {
   padding: 60px 0; //Maybe 60 minus font-size divided by two, if you want to be  exact
}

This will set the top and bottom padding of the div to 60px, and the left and right padding to zero, making the div 120px (plus the height of your font) high, and placing the text vertically centered in the div.

answered 4 years ago BAR #10

For reference and to add a simpler answer:

Pure CSS:

.vertical-align {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Or as a SASS/SCSS Mixin:

@mixin vertical-align {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Use by:

.class-to-center {
    @include vertical-align;
}

By Sebastian Ekström's blog post Vertical align anything with just 3 lines of CSS:

This method can cause elements to be blurry due to the element being placed on a “half pixel”. A solution for this is to set its parent element to preserve-3d. Like following:

.parent-element {
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;
}

We live in 2015+ and Flex Box is supported by every major modern browser.

It will be the way websites are made from here on out.

Learn it!

answered 4 years ago Dave #11

I needed a row of clickable elephants, vertically centered, but without using a table to get around some Internet Explorer 9 weirdness.

I eventually found the nicest CSS (for my needs) and it's great with Firefox, Chrome, and Internet Explorer 11. Sadly Internet Explorer 9 is still laughing at me...

div {
  border: 1px dotted blue;
  display: inline;
  line-height: 100px;
  height: 100px;
}

span {
  border: 1px solid red;
  display: inline-block;
  line-height: normal;
  vertical-align: middle;
}

.out {
  border: 3px solid silver;
  display: inline-block;
}
<div class="out" onclick="alert(1)">
  <div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>
  <div> <span>A lovely clickable option.</span> </div>
</div>

<div class="out" onclick="alert(2)">
  <div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>
  <div> <span>Something charming to click on.</span> </div>
</div>

Obviously you don't need the borders, but they can help you see how it works.

answered 4 years ago mPrinC #12

I would just like to extend the answer from @michielvoo in order to release need for line-height and breathing of div height. It is basically just simplified version like this:

div {
  width: 250px;
  /* height: 100px;
  line-height: 100px; */
  text-align: center;
  border: 1px solid #123456;
  background-color: #bbbbff;
  padding: 10px;
  margin: 10px;
}

span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
<div>
  <span>All grown-ups were once children... but only few of them remember it</span>
</div>

<div>
  <span>And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye.</span>
</div>

NOTE: commented out part of cssis needed for fixed-height of enclosing div.

answered 4 years ago Rahul #13

.element{position: relative;top: 50%;transform: translateY(-50%);}

Add this small code in the CSS property of your element. It is awesome. Try it!

answered 3 years ago Pranav Singh #14

The solution accepted as the answer is perfect to use line-height the same as the height of div, but this solution does not work perfectly when text is wrapped OR is in two lines.

Try this one if text is wrapped or is on multiple lines inside a div.

#box
{
  display: table-cell;
  vertical-align: middle;
}

For more reference, see:

answered 3 years ago bruceceng #15

Newer browsers now support the CSS calc function. If you are targeting these browsers you may want to look into doing something like this:

<div style="position: relative; width: 400px; height: 400px; background-color: red">
  <span style="position: absolute; line-height: 40px; height: 80px; text-align: center; width: 300px; overflow: hidden; top: calc(50% - 40px); left: calc(50% - 150px);">
    Here are two lines that will be centered even if the parent div changes size.
  </span>
</div>

The key is to use style = "top: calc(50% - [innerFixedHeightInPX/2]px); height: [innerFixedHeightInPX]px;" inside an absolute or relatively positioned parent div.

answered 3 years ago Gothburz #16

For all your vertical alignment needs!

Declare this Mixin:

@mixin vertical-align($position: relative) {
  position: $position;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Then include it in your element:

.element{
    @include vertical-align();
}

answered 3 years ago Marconi #17

Try this solution:

.EXTENDER {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    overflow-y: hidden;
    overflow-x: hidden;
}

.PADDER-CENTER {
    width: 100%;
    height: 100%;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
}
<div class="EXTENDER">
  <div class="PADDER-CENTER">
    <div contentEditable="true">Edit this text...</div>
  </div>
</div>

Built using CSS+.

answered 3 years ago Sajid #18

Here is working code:

body{
  margin:0;
}
div {
  height: 80px;
  background: #171717;
  font-size: 24px;
  text-align: center;
  font-style: normal;
  color: #FFF;
  margin-top: 18px;
  margin-left: 4px;
  line-height: 80px;
}
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Align text vertically center in div using CSS</title>
  </head>

  <body>
    <div>
      <span><a class="btn" href="http://ownanswers.com/"
               rel="dofollow">OwnAnswers.com</a>
      </span>
      For asking your questions, visit this site.
    </div>
  </body>
</html>

Result

Enter image description here

answered 2 years ago satwik boorgula #19

You can also use below properties.

display: flex; 
align-content: center; 
justify-content : center;

answered 2 years ago Manish Kumar #20

A very simple & most powerful solution to vertically align center:

.outer-div {
  height: 200px;
  width: 200px;
  text-align: center;
  border: 1px solid #000;
}

.inner {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  color: red;
}
<div class="outer-div">
  <span class="inner">No data available</span>
</div>

answered 2 years ago URL87 #21

Set it within button instead of div if you don't care about its little visual 3D effect.

#box
{
  height: 120px;
  width: 300px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
}
<button Id="box" disabled>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</button>

answered 2 years ago bourax webmaster #22

This works perfectly.

You have to use table style for the div and center align for the content.

answered 2 years ago Carles Alcolea #23

I'm not sure anyone has gone the writing-mode route, but I think it solves the problem cleanly and has a broad support:

.vertical {
  //border: 1px solid green;
  writing-mode: vertical-lr;
  text-align: center;
  height: 100%;
  width: 100%;
}
.horizontal {
  //border: 1px solid blue;
  display: inline-block;
  writing-mode: horizontal-tb;
  width: 100%;
  text-align: center;
}
.content {
  text-align: left;
  display: inline-block;
  border: 1px solid #e0e0e0;
  padding: .5em 1em;
  border-radius: 1em;
}
<div class="vertical">
  <div class="horizontal">
    <div class="content">
      I'm centered in the vertical and horizontal thing
    </div>
  </div>
</div>

This will, of course, work with any dimensions you need (besides 100% of the parent). If you uncomment the border lines, it'll be helpful to familiarize yourself.

JSFiddle demo for you to fiddle.

Caniuse support: 85.22% + 6.26% = 91.48% (even IE is in!)

answered 2 years ago user6781634 #24

.text{
   background:#ccc;  
   position:relative; 
   float:left; 
   text-align:center; 
   width:400px; 
   line-height:80px; 
   font-size:24px; 
   color:#000; 
   float:left;
 }

answered 2 years ago sstauross #25

Try the transform property:

 #box {
  height: 90px;
  width: 270px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
 <div Id="box">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

answered 2 years ago Ayyappan K #26

Wherever you want vertically center style means you can try display:table-cell and vertical-align:middle.

Example:

#box
{
  display: table-cell;
  vertical-align: middle;
  height: 90px;
  width: 270px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
  text-align: center;
  margin-top: 20px;
  margin-left: 5px;
}
<div Id="box">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>

answered 2 years ago MAChitgarha #27

Flexboxes that were introduced in CSS3 are the solution:

section {
    display: flex;
    display: -webkit-flex;
    height: 200px;
    width: 50%;
    margin: auto;
    border-radius: 20px;
    border: 5px solid black;
    background-color: yellow;
}

p {
    text-align: center;
    margin: auto; /* Important */
    font-family: Calibri;
}
<section>
    <p>
        I'm center!<br/>
        Flexboxes are great!
    </p>
</section>

Note: Replace the line above which marked as important with one of these lines, if you want to center the text:

1) Only vertically:

margin: auto 0;

2) Only horizontally:

margin: 0 auto;

UPDATE: As I noticed, this trick works with grids (display: grid), also.

answered 2 years ago Nikit Barochiya #28

<!DOCTYPE html>
<html>
  <head>
    <style>
      .main{
        height:450px;
        background:#f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        -webkit-box-align: center;
        align-items: center;
        justify-content: center;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div class="main">
      <h1>Hello</h1>
    </div>
  </body>
</html>

answered 1 year ago Akshay Pethani #29

You can use the following code snippet as the reference. It is working like a charm for me:

<!DOCTYPE html>
    <html lang="de">
        <head>
            <title>Vertically Center Text</title>
            <style>
                html, body {
                    height: 100%;
                    margin: 0;
                    padding: 0;
                    width: 100%;
                }
                body {
                    display: table;
                }
                .centered-text {
                    text-align: center;
                    display: table-cell;
                    vertical-align: middle;
                }
            </style>
        </head>

        <body style="background:#3cedd5">
            <div class="centered-text">
                <h1>Yes, it's my landing page</h1>
                <h2>Under construction, coming soon!!!</h2>
            </div>
        </body>
    </html>

The output of the above code snippet is as follow:

Enter image description here

Source code credit: How do I vertically center text with CSS? - Code Puran

answered 1 year ago antelove #30

.box {  
  width: 100%;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}

.height {
  line-height: 170px;
  height: 170px;
}

.transform { 
  height: 170px;
  position: relative;
}

.transform p {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<h4>Using Height</h4>
<div class="box height">
  Lorem ipsum dolor sit
</div>

<hr />

<h4>Using Transform</h4>
<div class="box transform">
  <p>Lorem ipsum dolor sit</p>
</div>

answered 10 months ago Rafiqul Islam #31

Try the following code:

display: table-cell;
vertical-align: middle;

div {
  height: 80%;
  width: 100%;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  background: #4CAF50;
  color: #fff;
  font-size: 50px;
  font-style: italic;
}
<div>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

answered 9 months ago Caner #32

The following code will put the div in the middle of the screen regardless of screen size or div size:

.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}
 <html>
 <head>
 </head>
 <body>
 <div class="center-screen">
 I'm in the center
 </div>
 </body>
 </html>

See more details about flex here.

answered 7 months ago Saravana priyan S #33

I saw the previous answers, and they will work only for that width of screen (not responsive). For the responsive you have to use flex.

Example:

div{ display:flex; align-item:center;}

answered 4 months ago Kumar #34

Even better idea for this. You can do like this too

body,
html {
  height: 100%;
}

.parent {
  white-space: nowrap;
  height: 100%;
  text-align: center;
}

.parent:after {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  content: '';
}

.centered {
  display: inline-block;
  vertical-align: middle;
  white-space: normal;
}
<div class="parent">
  <div class="centered">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
</div>

answered 3 months ago ArifMustafa #35

Absolute Positioning and Stretching

As with the method above this one begins by setting positioning on the parent and child elements as relative and absolute respectively. From there things differ.

In the code below I’ve once again used this method to center the child both horizontally and vertically, though you can use the method for vertical centering only.

html

<div id="parent">
    <div id="child">Content here</div>
</div>

css

#parent {position: relative;}
#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50%;
    height: 30%;
    margin: auto;
}

The idea with this method is to try to get the child element to stretch to all 4 edges by setting the top, bottom, right, and left vales to 0. Because our child element is smaller than our parent elements it can’t reach all 4 edges.

Setting auto as the margin on all 4 sides however causes opposite margins to be equal and displays our child div in the center of the parent div.

Unfortunately the above won’t work in IE7 and below and like the previous method the content inside the child div can grow too large causing it to be hidden.

answered 1 month ago Mohammad Fathi MiMFa #36

This is easy and very short:

.block {
  display: table-row;
  vertical-align: middle;
}

.tile {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 500px;
  height: 100px;
}
<div class="body">
  <span class="tile">
    Hello middle world! :)
  </span>
</div>

comments powered by Disqus