Put a <div> element in the horizon and vertical center of the screen?

1k Views Asked by At

Here is my code:

div {
  position: absolute;
  top: 50%;
  left: 50%;
  text-align: center;
  margin: 0;
  padding: 0;
}
<div>This sentence should be displayed in the center of the whole screen

</div>

I tried margin and padding to make the div in the center of the whole screen. (horizonly and vertically). However, neither margin nor padding can center the element.

Then I tried left: 50% and top:50%, it changes the position of the element, but not as expected. The left margin of <div> is located to left:50%, while I want the center of <div> to be located to left:50%..

Does anyone have ideas about this?

8

There are 8 best solutions below

0
On
div {
    position: absolute;
    top: 50%;
    left: 50%;
    text-align: center;
    margin: 0;
    padding: 0;
    transform: translate(-50%, -50%);
}
0
On

use - transform: translate

div {
    position: absolute;
    top: 50%;
    left: 50%;
    text-align: center;
    margin: 0;
    padding: 0;
    background: #ccc;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
        transform: translate(-50%,-50%);
}
<div>This sentence should be displayed in the center of the whole screen</div>

0
On

Try like this: Demo

html, body {
    height: 100%;
}
body {
    display: table;
    margin: 0 auto;
}
div {
    height: 100%;
    display: table-cell;
    vertical-align: middle;
}
0
On

Try this fiddle.

div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 200px;
  height: 50px;
}
0
On

This should help you.
You need to use the transform:translate css.

div {
        position: fixed;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);

    }

Fiddle here

0
On

Here you go. Keep position as relative and text-align it to center, if you don't want to use translate.

div {
position: relative;
text-align:center;
}

here is the fiddle

0
On

Try this:

 div {
      position: relative;
      text-align:center;
      top:50%;
    }
0
On

Its Simple and Responsive try this

div {
  margin: auto;
  width:50%;
}

Working Fiddle Here