By shinjuo


2010-05-30 19:02:13 8 Comments

I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.

.testimonialText {
  position: absolute;
  left: 15px;
  top: 15px;
  width: 150px;
  height: 309px;
  vertical-align: middle;
  text-align: center;
  font-family: Georgia, "Times New Roman", Times, serif;
  font-style: italic;
  padding: 1em 0 1em 0;
}
<div class="testimonialText">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

30 comments

@Mimina 2019-10-31 06:56:13

Flexbox worked perfectly for me, centering multiple elements inside parent div horizontally & vertically.

HTML-Code:

<div class="parent-div">
    <div class="child-div">
      <a class="footer-link" href="https://www.github.com/">GitHub</a>
      <a class="footer-link" href="https://www.facebook.com/">Facebook</a>
      <p class="footer-copywrite">© 2019 Lorem Ipsum.</p>
    </div>
  </div>

CSS-Code:
Code below stacks all elements inside of parent-div in a column, centering the elements horizontally & vertically. I used the child-div to keep the two Anchor elements on same line (row). Without child-div all three elements (Anchor, Anchor & Paragraph) are stacked inside parent-div's column on top of each other. Here only child-div is stacked inside parent-div column.

/* */
.parent-div {
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

@Kerim092 2018-05-15 19:05:56

Try this, add on the parent div:

display: flex;
align-items: center;

@Casper Skovgaard 2019-06-18 14:44:04

I like this one - Simple and works in modern browsers

@Adam Tomat 2012-11-22 15:18:12

Here's a great resource

From http://howtocenterincss.com/:

Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors. This consolidates them and gives you the code you need for each situation.

Using Flexbox

Inline with keeping this post up to date with the latest tech, here's a much easier way to center something using Flexbox. Flexbox isn't supported in Internet Explorer 9 and lower.

Here are some great resources:

JSFiddle with browser prefixes

li {
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
  /* Column | row */
}
<ul>
  <li>
    <p>Some Text</p>
  </li>
  <li>
    <p>A bit more text that goes on two lines</p>
  </li>
  <li>
    <p>Even more text that demonstrates how lines can span multiple lines</p>
  </li>
</ul>

Another solution

This is from zerosixthree and lets you center anything with six lines of CSS

This method isn't supported in Internet Explorer 8 and lower.

jsfiddle

p {
  text-align: center;
  position: relative;
  top: 50%;
  -ms-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}
<ul>
  <li>
    <p>Some Text</p>
  </li>
  <li>
    <p>A bit more text that goes on two lines</p>
  </li>
  <li>
    <p>Even more text that demonstrates how lines can span multiple lines</p>
  </li>
</ul>

Previous answer

A simple and cross-browser approach, useful as links in the marked answer are slightly outdated.

How to vertically and horizontally center text in both an unordered list and a div without resorting to JavaScript or CSS line heights. No matter how much text you have you won't have to apply any special classes to specific lists or divs (the code is the same for each). This works on all major browsers including Internet Explorer 9, Internet Explorer 8, Internet Explorer 7, Internet Explorer 6, Firefox, Chrome, Opera and Safari. There are two special stylesheets (one for Internet Explorer 7 and another for Internet Explorer 6) to help them along due to their CSS limitations which modern browsers don't have.

Andy Howard - How to vertically and horizontally center text in an unordered list or div

As I didn't care much for Internet Explorer 7/6 for the last project I worked on, I used a slightly stripped down version (i.e. removed the stuff that made it work in Internet Explorer 7 and 6). It might be useful for somebody else...

JSFiddle

.outerContainer {
  display: table;
  width: 100px;
  /* Width of parent */
  height: 100px;
  /* Height of parent */
  overflow: hidden;
}

.outerContainer .innerContainer {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
  margin: 0 auto;
  text-align: center;
}

li {
  background: #ddd;
  width: 100px;
  height: 100px;
}
<ul>
  <li>
    <div class="outerContainer">
      <div class="innerContainer">
        <div class="element">
          <p>
            <!-- Content -->
            Content
          </p>
        </div>
      </div>
    </div>
  </li>

  <li>
    <div class="outerContainer">
      <div class="innerContainer">
        <div class="element">
          <p>
            <!-- Content -->
            Content
          </p>
        </div>
      </div>
    </div>
  </li>
</ul>

@Adam Tomat 2013-02-06 16:57:11

No problem. I still prefer using height: x; line-height: x; but more often then not I need multiple lines of text. That's why I love this solution. Simple, reusable, cross-browser, no js and only requires a little extra mark up.

@Thomas David Baker 2013-03-08 17:49:51

If the text is larger than the box it will overflow. I've tried various ways to prevent the overflow but they all seemingly conflict with table and table-cell display. As soon as I restrict the overflow the vertical centering stops working. jsfiddle.net/2HHLE Any ideas?

@Thomas David Baker 2013-03-09 02:40:27

To answer my own question if you put the table/table-cell div(s) into another div with fixed width/height and overflow:hidden that will do the trick. I wrote it up at bluebones.net/2013/03/…

@Adam Tomat 2013-03-11 10:30:59

@ThomasDavidBaker, the other solution if you need these to be dynamic is to set a 100% height. Here's a jsfiddle, basically just changed height: 100px; to height: 100%; for both the li and for .outerContainer.

@Stano 2013-07-29 07:04:30

+1, only to mention, this works only for statically and relatively positioned containers, not for absolute and fixed positions: jsfiddle.net/Sw3Jd/128

@Adam Tomat 2013-07-29 07:27:59

@stano, that jsfiddle is missing some markup required to make this solution work. See this updated fiddle where there's a working fixed and absolutely positioned LI: http://jsfiddle.net/Sw3Jd/130/

@Stano 2013-07-29 08:11:48

Hi Adam, it was my mistake, you're right it works well with that bit more markup. Thanks for your time and the explanation.

@Gnagy 2014-06-26 12:14:25

Don't want to be a nosepicker here but in the second solution from zerosixthree. There is a typo in the CSS at "- wekbit -transform: translateY(-50%);" Still, many thanks!! Great solution!

@Fergal 2016-03-25 01:48:33

This is what I'm using since it works in all situations that I've encountered. I created a SCSS mixin to keep the code tight.

@Kathara 2017-04-13 11:35:47

Flexbox for the win! It has already saved me a lot of trouble but I didn't think it would work for text as well. Thanks for updating your answer! :)

@JAT86 2018-03-30 23:22:33

For over a year, I avoided display:flex as I had thought it was new and not widely supported. Then I tried testing display table, absolute positioning, viewport height, and other stuff involving margin and padding adjustments. After so much months of frustration, I have come to accept that the only solution for this problem that truly works is display flex.

@igorGIS 2019-09-09 10:56:09

In your first example you do not mention you use 'text-align: center', but it present in fiddle example, if remove it, the items (text or whatever) still align to left side

@mike 2014-01-17 23:57:18

Try to embed a table element.

<div>
  <table style='width:200px; height:100px;'>
    <td style='vertical-align:middle;'>
      copenhagen
    </td>
  </table>
</div>

@Micros 2014-02-04 10:44:50

Tables are only for dealing with tabular data. They should never be used to fix layout problems.

@MC9000 2014-06-13 22:20:01

Nice thing about tables though, is they are always consistent - CSS is interpreted so many different ways and putting nested DIVs in just to get something simple done adds extra HTML (and confusion). CSS is still grossly flawed

@T4NK3R 2014-07-27 17:07:03

Yes, Unfortunately this IS STILL the only reliable way to vertically align (unknown) text in a block. Why do the CSS gods hate valign so much ? (ALL browser CAN do it consistently - but only in table cells)

@ezzato 2018-06-21 10:57:35

Using CSS grid did it for me:

.outer {
  background-color: grey;
  width: 10rem;
  height: 10rem;
  display: grid;
  justify-items: center;
}

.inner {
  background-color: red;
  align-self: center;
}
<div class='outer'>
  <div class='inner'>
    Content
  </div>
</div>

@Nidhin Joseph 2019-08-11 00:03:07

You can use css flexbox.

.testimonialText {
  height: 500px;
  padding: 1em;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #b4d2d2;
}
<div class="testimonialText">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

@Toni Michel Caubet 2014-09-15 17:54:25

These days (we don't need Internet Explorer 6-7-8 any more) I would just use CSS display: table for this issue (or display: flex).


For older browsers:

Table:

.vcenter {
    display: table;
    background: #eee; /* optional */
    width: 150px;
    height: 150px;
    text-align: center; /* optional */
}

.vcenter > :first-child {
    display: table-cell;
    vertical-align: middle;
}
<div class="vcenter">
  <p>This is my Text</p>
</div>

Flex:

.vcenter {
    display: flex; /* <-- Here */
    align-items: center; /* <-- Here */
    justify-content: center; /* optional */
    height: 150px; /* <-- Here */
    background: #eee;  /* optional */
    width: 150px;
}
<div class="vcenter">
  <p>This is my text</p>
</div>


This is (actually, was) my favorite solution for this issue (simple and very well browser supported):

div {
    margin: 5px;
    text-align: center;
    display: inline-block;
}

.vcenter {
    background: #eee;  /* optional */
    width: 150px;
    height: 150px;
}
.vcenter:before {
    content: " ";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    max-width: 0.001%; /* Just in case the text wrapps, you shouldn't notice it */
}

.vcenter > :first-child {
    display: inline-block;
    vertical-align: middle;
    max-width: 99.999%;
}
<div class="vcenter">
  <p>This is my text</p>
</div>
<div class="vcenter">
  <h4>This is my Text<br/>Text<br/>Text</h4>
</div>
<div class="vcenter">
  <div>
   <p>This is my</p>
   <p>Text</p>
  </div>
</div>

@Dan H 2015-01-12 14:50:25

@Imray he's basically adding a 0px width inline-block element next to the text (the pseudo :before). However, this faux block has a 100% height, which is the trick. As the block and text are both v-aligned, it renders as intended.

@Rocco 2015-02-04 00:27:42

best answer, clean solution, IE8 supported

@trgraglia 2015-03-18 13:04:16

When the text wraps, you can have issues with this. I fixed it by adding the following to the nested element: width:95%;vertical-align:middle;

@beta 2016-07-19 14:32:43

if the text is too long, it doesn't work. do you have a solution? jsfiddle.net/cyxuy95q

@Toni Michel Caubet 2016-07-19 15:17:29

As suggested in the previous comment to yours, set max-width 95% jsfiddle.net/cyxuy95q/1

@Alex78191 2018-11-16 15:39:42

IE8 supports display: table

@Sulaymon Hursanov 2019-03-23 18:24:00

Margin auto on a grid-item.

Similarly to Flexbox, applying margin auto on a grid-item centers it on both axes:

.container {
  display: grid;
}
.element {
  margin: auto;
}

@Sanjeet kumar 2018-05-15 20:00:36

Use:

h1 {
    margin: 0;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.container {
    height: 200px;
    width: 500px;
    position: relative;
    border: 1px solid #eee;
}
<div class="container">
    <h1>Vertical align text</h1>
</div>

With this trick, you can align anything if you don't want to make it center add "left:0" to align left.

@Vlad 2018-01-30 09:42:24

This works fine:

HTML

<div class="information">
    <span>Some text</span>
    <mat-icon>info_outline</mat-icon>
</div>

Sass

.information {
    display: inline-block;
    padding: 4px 0;
    span {
        display: inline-block;
        vertical-align: middle;
    }
    mat-icon {
        vertical-align: middle;
    }
}

Without and with the image tag <mat-icon> (which is a font).

@Leon Rom 2017-08-30 11:58:59

According to Adam Tomat's answer there was prepared a JSFiddle example to align the text in div:

<div class="cells-block">    
    text<br/>in the block   
</div>

by using display:flex in CSS:

.cells-block {
    display: flex;
    flex-flow: column;
    align-items: center;       /* Vertically   */
    justify-content: flex-end; /* Horisontally */
    text-align: right;         /* Addition: for text's lines */
}

with another example and a few explanations in a blog post.

@Nikit Barochiya 2017-03-17 05:07:01

<!DOCTYPE html>
<html>

  <head>
    <style>
      .container {
        height: 250px;
        background: #f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>

</html>

@Chiwda 2017-09-13 09:42:43

Worked like a charm when vertical-align: middle; and all the rest failed.

@Cyan Baltazar 2016-12-21 02:39:58

You can align center text vertically inside a div using Flexbox.

<div>
   <p class="testimonialText">This is the testimonial text.</p>
</div>

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

You can learn more about it at A Complete Guide to Flexbox.

@dimitar 2016-09-21 13:53:36

A simple solution to an element of not knowing values:

HTML

<div class="main">
    <div class="center">
        whatever
    </div>
</div>

CSS

.main {
    position: relative
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}

@Roman Pokrovskij 2016-02-18 13:03:32

Using flex, be careful with differences in browsers' rendering.

This works well both for Chrome and Internet Explorer:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #fcc;
}
<div class="outer"><div class="inner">Active Tasks</div></div>

Compare with this one that works only with Chrome:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    background-color: #fcc;
}
<div class="outer">
<div class="inner"><span style=" margin: auto;">Active Tasks</span></div>
</div>

@Raul Fernandez Marques 2015-12-12 20:25:21

It is easy with display: flex. With the following method, the text in the div will be centered vertically:

div {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  /* More style: */
  height: 300px;
  background-color: #888;
}
<div>
  Your text here.
</div>

And if you want, horizontal:

div {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  justify-content: center;
  /* More style: */
  height: 300px;
  background-color: #888;
}
<div>
  Your text here.
</div>

You must see the browser version you need; in old versions the code doesn’t work.

@splashout 2016-12-13 21:56:29

Short and sweet... the way it should be to do something so simple. Works on IE 11, Chrome and Firefox... good enough for me

@user4275029 2016-12-23 13:18:05

This answer works with positioning text inside foreign objects in svg. Thanks!

@DenisKolodin 2017-01-20 07:32:35

I believe: Flex is remedy for everything!

@DenisKolodin 2017-01-20 09:52:25

text-align: center is necessary too, because long text fill width and will be aligned left

@jokab 2018-07-15 03:53:38

needs to be applied to parent div to work

@Jed Lynch 2018-10-30 02:25:01

I always had trouble with this, and I absolutely hate the answer of increasing the line height. This worked really well.

@Michelangelo 2019-06-24 15:14:31

This is the best answer, but I still think that text alignment should be independent of how you display an element. It is still weird to me that you need to use flex or older methods to do this. A propterty like: vertical-align-text could solve a lot of frustration.

@Justin 2015-07-30 20:34:41

This is the cleanest solution I have found (Internet Explorer 9+) and adds a fix for the "off by .5 pixel" issue by using transform-style that other answers had omitted.

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

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

Source: Vertical align anything with just 3 lines of CSS

@Craig 2014-10-08 06:50:52

Here is a solution that works best for a single line of text.

It can also work for multi-lined text with some tweaking if the number of lines is known.

.testimonialText {
    font-size: 1em; /* Set a font size */
}
.testimonialText:before { /* Add a pseudo element */
    content: "";
    display: block;
    height: 50%;
    margin-top: -0.5em; /* Half of the font size */
}

Here is a JSFiddle.

@Dhiraj 2014-10-03 07:18:49

There are several tricks to display content or an image in the center of a div. Some of the answers are really nice and I am fully agree with these too.

Absolute Horizontal And Vertical Centering In CSS

http://www.css-jquery-design.com/2013/12/css-techniques-absolute-horizontal-and-vertical-centering-in-css/

There are more than 10 techniques with examples. Now it's up to you which you prefer.

No doubt, display:table; display:table-Cell is a better trick.

Some good tricks are the following:

Trick 1 - By using display:table; display:table-cell

HTML

<div class="Center-Container is-Table">
  <div class="Table-Cell">
    <div class="Center-Block">
        CONTENT
    </div>
  </div>
</div>

CSS Code

.Center-Container.is-Table { display: table; }
.is-Table .Table-Cell {
  display: table-cell;
  vertical-align: middle;
}
.is-Table .Center-Block {
  width: 50%;
  margin: 0 auto;
}

Trick 2 - By using display:inline-block

HTML

<div class="Center-Container is-Inline">
  <div class="Center-Block">
     CONTENT
  </div>
</div>

CSS code

.Center-Container.is-Inline {
  text-align: center;
  overflow: auto;
}

.Center-Container.is-Inline:after,
.is-Inline .Center-Block {
  display: inline-block;
  vertical-align: middle;
}

.Center-Container.is-Inline:after {
  content: '';
  height: 100%;
  margin-left: -0.25em; /* To offset spacing. May vary by font */
}

.is-Inline .Center-Block {
  max-width: 99%; /* Prevents issues with long content causes the content block to be pushed to the top */
  /* max-width: calc(100% - 0.25em) /* Only for Internet&nbsp;Explorer 9+ */
}

Trick 3 - By using position:relative;position:absolute

<div style="position: relative; background: #ddd; border: 1px solid #ddd; height: 250px;">
  <div style="width: 50%; height: 60%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: #ccc; text-align: center;">
    <h4>ABSOLUTE CENTER, <br/>
WITHIN CONTAINER.</h4>
    <p>This box is absolutely centered, horizontally and vertically, within its container</p>
  </div>
</div>

@ankit sigdel 2014-08-25 08:59:01

HTML

<div class="relative"><!--used as a container-->
    <!-- add content here to to make some height and width
    example:<img src="" alt=""> -->
    <div class="absolute">
        <div class="table">
            <div class="table-cell">
                Vertical contents goes here
            </div>
        </div>
    </div>
</div>

CSS

 .relative {
     position: relative;
 }
 .absolute {
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
     background: rgba(0, 0, 0, 0.5);
 }
 .table {
     display: table;
     height: 100%;
     width: 100%;
     text-align: center;
     color: #fff;
 }
 .table-cell {
     display: table-cell;
     vertical-align: middle;
 }

@Davors 2014-06-07 08:14:13

Check this simple solution:

HTML

<div class="block-title"><h3>I'm a vertically centered element</h3></div>

CSS

.block-title {
    float: left;
    display: block;
    width: 100%;
    height: 88px
}

.block-title h3 {
    display: table-cell;
    vertical-align: middle;
    height: inherit
}

JSFiddle

@Earl Hickey 2014-05-25 20:42:21

There's a simpler way to vertically align the content without resorting to table/table-cell:

http://jsfiddle.net/bBW5w/1/

In it I have added an invisible (width=0) div that assumes the entire height of the container.

It seems to work in Internet Explorer and Firefox (latest versions). I didn't check with other browsers

  <div class="t">
     <div>
         everything is vertically centered in modern IE8+ and others.
     </div>
      <div></div>
   </div>

And of course the CSS:

.t, .t > div:first-child
{
    border: 1px solid green;
}
.t
{
    height: 400px;
}
.t > div
{
    display: inline-block;
    vertical-align: middle
}
.t > div:last-child
{
    height: 100%;
}

@Shadrack B. Orina 2012-04-18 15:15:51

You can do this by setting the display to 'table-cell' and applying a vertical-align: middle;:

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

This is however not supported by all versions of Internet Explorer according to this excerpt I copied from http://www.w3schools.com/cssref/pr_class_display.asp without permission.

Note: The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by Internet Explorer 7 and earlier. Internet Explorer 8 requires a !DOCTYPE. Internet Explorer 9 supports the values.

The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp.

Enter image description here

@Brian Low 2012-07-15 17:56:51

Great idea! display:table-cell has other effects but if you are okay with them this is a nice solution

@Elan Perach 2013-02-06 10:46:02

Also important to add the height of the element.

@TheJeff 2017-12-20 16:12:24

Unfortunately overflow: hidden doesn't work on display: table-cell

@Robert Harvey 2010-05-30 19:29:50

Vertical Centering in CSS
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Article summary:

For a CSS 2 browser, one can use display:table/display:table-cell to center content.

A sample is also available at JSFiddle:

div { border:1px solid green;}
<div style="display: table; height: 400px; overflow: hidden;">
  <div style="display: table-cell; vertical-align: middle;">
    <div>
      everything is vertically centered in modern IE8+ and others.
    </div>
  </div>
</div>

It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using # to hide styles from newer browsers:

div { border:1px solid green;}
<div style="display: table; height: 400px; #position: relative; overflow: hidden;">
  <div style=
    "#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
    <div style=" #position: relative; #top: -50%">
      everything is vertically centered
    </div>
  </div>
</div>

@Bakhtiyor 2011-06-03 11:54:31

second link is better solution though

@gregorvand 2012-10-20 23:04:21

the first link's example is broken for Chrome, so not as reliable now

@Raul 2013-01-19 10:47:55

First link is better I think even though it looks complicated cause the second link uses just one row of text or an image of which you know the height. What if you have 2 or 3 rows of text or if you don't know the height of your text, cause it varies. How would that work with line-height? So to sum up. I tested the first version and it works on IE, Firefox AND CHROME.

@malisokan 2013-09-04 12:00:59

First link (jakpsatweb) works best for me in IE8-IE10, FF 23, Chrome 29 and on iPad, iPhone

@Alexander.Iljushkin 2014-01-23 21:14:00

I don't understand, why we should to subvert with this stuff ? It's 21st century! why they just don't include one damn option for aligning damn text vertically in css... like so: content-centering: both or vertically or horisontally. it's just unbelieveable that tecnology used for years are so dumb.

@nothingisnecessary 2014-09-08 16:34:03

@Flextra: This is why folks still use tables for grid layout. Vertical align (or anything with height & dynamic data) can be challenging with pure CSS. You have to be willing to do weird hacks like this (somewhat defeats the "separating content from layout" idea), or take the multi-pass rendering hit and use non-static tables. I've never once had complaints from end users for table despite that I routinely break CSS fanboys' hearts. Most of em design only simple blogs & static sites. Some of us build business software and need dense data display, and our users care more about functionality.

@nothingisnecessary 2014-09-08 16:41:36

Yep. Don't get me wrong, if I build a "site" I go with lean html and prefer pure CSS, but I dunno how many times I wrestled with lining stuff up for hours, when I just said 'F it' and used a table. Things are better now, but some of us who make business web apps have to support older browsers (IE6 is still in use at some clients!), while people who make blogs can live in the clouds and pretend that everybody in the world has a fast connection, new computer, and the latest version of X browser with CSS 3, etc. Case in point: some Jira plugins use single-row tables for layout (or did anyway)

@Desty 2015-02-06 12:28:46

It is quite ludicrous that tables are frowned upon as some kind of old-fashioned hack only a newbie would use, and here we are using "display:table-cell" in a DIV as a far hackier workaround.

@Dan Beaulieu 2015-04-21 19:17:32

@Desty, the first time you bootstrap a website that was built using thousands of tables you'll realize why they're frowned upon.

@Erick Petrucelli 2015-08-19 22:42:07

I believe it's time to update the accepted answer, covering the new Flexbox way.

@Vicky Chijwani 2017-10-05 23:23:22

@Alexander.Iljushkin it's not dumb, it's just wasn't designed for this. CSS was designed for hyperlinked text documents, not rich web apps. Think Wikipedia, not YouTube. So yes, CSS sucks for apps, I 100% agree. But nobody foresaw that the web would become an application platform, let alone the biggest application platform ever. This fact has only come into sharp focus with the rise of React though, with its philosophy of separating actual concerns (components), rather than simply separating by filetype (HTML / CSS / JS).

@Alex78191 2018-11-16 15:27:37

display:table doesn't worked for me.

@Stefan 2019-06-03 19:30:48

And now suddenly overflow:hidden no longer works for the div when I use display:table-cell... go figure.

@David 2011-02-06 19:21:23

You need to add the line-height attribute and that attribute must match the height of the div. In your case:

.center {
  height: 309px;
  line-height: 309px; /* same as height! */
}
<div class="center">
  A single line.
</div>

In fact, you could probably remove the height attribute altogether.

This only works for one line of text though, so be careful.

@WEFX 2011-11-01 18:51:51

I believe that's only valid if you have a single line of text in the div.

@David 2012-02-05 20:15:08

Absolutely, you'd have crazy line spacing in your text if it ran on more than 1 line.

@Adam Tomat 2013-09-05 10:48:08

@BobChatting, Yep it does. See my answer for a solution that allows multiple lines of text.

@Michael 2014-05-07 15:17:07

line-height propagates to every children

@Craig 2014-10-08 06:09:24

You can also use line-height:0 and enter a :before Pseudo element like jsfiddle.net/em0qdh3j again this is only for a single line however it allows percentage based heights unlike this solution.

@albanx 2015-07-02 13:41:52

not working with percent: height:100%; line-height:100%

@rorykoehler 2016-06-02 09:34:35

works beautifully for icons in a div (like a circle for example)

@Matthew Lock 2016-06-17 02:44:06

So counter-intuitive isn't it. One day someone will make a new language that will compile out to CSS but have rational DWI commands to control layout.

@GreeKatrina 2017-05-22 19:25:31

@albanx Using percentages in line-height refers to the font size of the element itself. Therefore, line-height: 100%; is the same as line-height: 1em;, and not 100% of the parent's height.

@aroth 2018-05-10 14:19:26

This feels incredibly hacky but somehow also less hacky than setting the element to display: table-cell just to take advantage of the fact that table-cell is the only display mode that lets you vertically center text in any reasonable way.

@PhilipRoman 2018-12-29 22:02:26

This does not work in mobile Chrome.

@Taiga 2019-01-27 18:31:51

worked like a charm. thanks for sharing!

@Dexter_ns88 2013-09-09 08:41:47

If you need to use with the min-height property you must add this CSS on:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

@Jonny Forney 2015-04-02 01:42:20

CSS:

.vertical {
   display: table-caption;
}

Add this class to the element that contains the things you want to align vertically

@Stephen Quan 2014-07-31 09:38:23

This is another variation of the div in a div pattern using calc() in CSS.

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

This works, because:

  • position:absolute for precise placement of the div within a div
  • we know the height of the inner div because we set it to 20px.
  • calc(50% - 10px) for 50% - half the height for centering the inner div

@Toni Michel Caubet 2016-06-20 07:40:14

The parent div would need position: relative

@Stefan van den Akker 2014-01-24 14:11:06

I use the following to vertically center random elements easily:

HTML:

<div style="height: 200px">
    <div id="mytext">This is vertically aligned text within a div</div>
</div>

CSS:

#mytext {
    position: relative;
    top: 50%; 
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

This centers the text in my div to the exact vertical middle of a 200px-high outer div. Note that you may need to use a browser prefix (like -webkit- in my case) to make this work for your browser.

This works not only for text, but also for other elements.

@Wilf 2014-07-25 20:09:11

I got more reliable results with position: absolute; - Thanks! N.B. You might want to included -ms-transform or IE will stuff something else up

@Shina 2015-01-27 17:10:14

I consider this the best answer, works 100% even inside absolute div

@sakovias 2016-04-01 12:52:26

Plunker suggests to put -web-kit-transform before transform. Perhaps adding -ms-transform can solve @ToniMichelCaubet's issue.

@Jeff Ward 2014-04-04 19:00:30

Hmm, there're obviously many ways to solve this.

But I have a <div> that's positioned absolutely, height:100% (actually, top:0;bottom:0 and fixed width) and display:table-cell just didn't work to center text vertically. My solution did require an inner span element, but I see many of the other solutions do also, so I might as well add it:

My container is a .label and I want the number vertically centered in it. I did it by positioning absolutely at top:50% and setting line-height:0

<div class="label"><span>1.</span></div>

And the CSS is as follows:

.label {
    position:absolute;
    top:0;
    bottom:0;
    width:30px;
}

.label>span {
    position:absolute;
    top:50%;
    line-height:0;
}

See it in action: http://jsfiddle.net/jcward/7gMLx/

@Tomas Tintera 2014-04-08 07:29:58

Nice because it's simplest solution. Downside is it works only for single line text, see fork of the example with longer text. jsfiddle.net/6sWfw

Related Questions

Sponsored Content

44 Answered Questions

[SOLVED] How to disable text selection highlighting

102 Answered Questions

[SOLVED] How to horizontally center a <div>

35 Answered Questions

[SOLVED] How to vertically align an image inside a div

38 Answered Questions

[SOLVED] How do I vertically center text with CSS?

21 Answered Questions

[SOLVED] Vertically align text next to an image?

1 Answered Questions

[SOLVED] Changing JQuery to affect colour of button, not background?

  • 2019-01-12 19:11:16
  • Toby
  • 37 View
  • -1 Score
  • 1 Answer
  • Tags:   jquery html css

2 Answered Questions

[SOLVED] jQuery + Regex to change CSS of first couple of Words

  • 2013-12-26 19:09:20
  • ipetduckies
  • 210 View
  • -3 Score
  • 2 Answer
  • Tags:   jquery css regex

2 Answered Questions

[SOLVED] submit button doesn't work with html code

  • 2016-11-25 14:33:25
  • Wavelet
  • 895 View
  • 1 Score
  • 2 Answer
  • Tags:   jquery html

1 Answered Questions

[SOLVED] Position button material design

1 Answered Questions

[SOLVED] centering an image while text covers both canvas (left and right)

  • 2014-11-09 14:11:47
  • robue-a7119895
  • 93 View
  • 4 Score
  • 1 Answer
  • Tags:   html css

Sponsored Content