49

I have a css class defined so I can make a div to use all the browser's viewport, the rule is the following:

.fullscreenDiv {
    background-color: #e8e8e8;
    width: 100%;
    height: auto;
    bottom: 0px;
    top: 0px;
    left: 0;
    position: absolute;
}

Now I want the text inside the div to be in the exact center of the screen so, vertical align center and horizontal align middle, but I can't seem to find the proper way to do so.

It only needs to work on webkit based browsers.

I already tried to add a P element inside with display set to table-cell (a common way of centering text) without luck.

Any suggestions?

  • 4
    ```text-align: center; position: absolute; top: 50%; bottom: 50%; width: 100%;``` - This should work better than the accepted answer - Add the styles to your bit of text – James111 Feb 23 '16 at 23:30

4 Answers4

83

The accepted answer works, but if:

  • you don't know the content's dimensions
  • the content is dynamic
  • you want to be future proof

use this:

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

More information about centering content in this excellent CSS-Tricks article.


Also, if you don't need to support old browsers: a flex-box makes this a piece of cake:
.center{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/

agconti
  • 17,780
  • 15
  • 80
  • 114
55

The standard approach is to give the centered element fixed dimensions, and place it absolutely:

<div class='fullscreenDiv'>
    <div class="center">Hello World</div>
</div>​

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}​
Zhanger
  • 1,290
  • 14
  • 19
calebds
  • 25,670
  • 9
  • 46
  • 74
3

There is no pure CSS solution to this classical problem.

If you want to achieve this, you have two solutions:

  • Using a table (ugly, non semantic, but the only way to vertically align things that are not a single line of text)
  • Listening to window.resize and absolute positionning

EDIT: when I say that there is no solution, I take as an hypothesis that you don't know in advance the size of the block to center. If you know it, paislee's solution is very good

Samuel Rossille
  • 18,940
  • 18
  • 62
  • 90
1

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

Ryan
  • 5,644
  • 3
  • 38
  • 66