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
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.
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.
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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With