css: how to center box div element directly in center?

top and left correspond to the top-left corner of your box. What you're trying to do is have them correspond to the center. So if you set margin-top and margin-left to negative of one-half the height and width respectively, you'll get a centered box.

Example for a 300x200 box:

width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -100px;

using translate will perfectly achieve that. simply apply this

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

source


Horizontal: Use a fixed width and

margin-left: auto;
margin-right: auto;

vertical: That's not that easy. You could use

display: table-cell 

for the surrounding DIV and then give it a

vertical-align: middle

Tags:

Css