Rasik
Rasik

Reputation: 903

How to centre a div vertically and horizontallly?

I have a div that I want to position at the center of a page(both vertically and horizontally).

For centring it horizontally I used the center tags around the div and for vertically centring it is tried a couple of things but none of them actually working.

Check out the code:

CSS:

.vcenter{
  height: 50px;
  width: 50px;
  background: red;
  vertical-align: middle;
  margin-top: calc(50% - 25px);
}

HTML :

<center>
    <div class="vcenter">

    </div>
<center>

Also I don't think using centre tags around the the div to centre an object is the best way to so it.

What I want to know is

Upvotes: 2

Views: 1365

Answers (2)

John Specko
John Specko

Reputation: 307

#divId {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

The only thing that isn't obvious is the transform takes into account the size of the element.

Upvotes: 3

Yosef Weiner
Yosef Weiner

Reputation: 5751

If available, using flex is the easiest. Apply these styles to the container in which you want to center your div:

display: flex;
align-items: center;
justify-content: center;

Upvotes: 4

Related Questions