Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

center a div box in the middle of the page using css

Tags:

css

I want to center a div right in the middle of the page, I tried top:30%, but when the window is resized off the alignment.

<div id=cent></div>

Thanks Jean

like image 959
X10nD Avatar asked Mar 23 '10 06:03

X10nD


People also ask

How do I center a div box in CSS?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I fix a div in the middle of my screen?

If your div has a known width and height, then you basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.


3 Answers

If you know the height/width of that div (for instance, it will be 100px X 200px) then you can do it like this:

#cent {
  position:absolute;
  top:50%;
  left:50%;
  margin-top:-50px; /* this is half the height of your div*/  
  margin-left:-100px; /*this is half of width of your div*/
}

UPDATE: another option: see http://www.w3.org/Style/Examples/007/center (Centering vertically)

like image 83
naivists Avatar answered Nov 02 '22 04:11

naivists


I know this question is pretty old, but I stumbled upon it, and I'll probably look for it again in the future.

In my case, the content has a variable height, and I don't want to use absolute positioning, so I used a flexbox container instead. You just need to wrap your content inside a div with the following style:

.container {
  min-height: 100vh; /* minimum height = screen height */
  display: flex;
  justify-content: center;
  align-items: center;
}

Example: https://codepen.io/alephao/pen/mdPRYqZ

like image 6
alephao Avatar answered Nov 02 '22 03:11

alephao


I know this question is 9 years old, but having stumbled upon it 9 years later, maybe someone else could do the same.

This is my working solution:

#cent {
  position: absolute;
  width: 500px;
  height: 500px;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

By doing this it will set the width and height to 500px, then it will set the top, left, right and bottom constraints to 0, and finally, by setting the margins to auto, the box will be put in the exact middle of the window. This will also be responsive.

like image 3
edoriggio Avatar answered Nov 02 '22 03:11

edoriggio