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 300×200 box:

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

Leave a Comment