I am trying to centre, just using css, a div element both vertically and horizontally.
All the examples I have seen makes use of hardcoded values like pixel values.
Should it be possible to centre a div element without using javascript and using just percentage values?
Here is my test: jsfiddle.net
You need to know the size of the div. (Yes, the div must have a size FIXED).
div {
width: 50px;
height: 50px;
}
His div must have absolute position:
div {
position: absolute;
width: 50px;
height: 50px;
}
After, you must enclose the top and left at 50%;
div {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
}
Finally, you must add a negative margin for both top and left referring to half the value of the height and width of your div.
div {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
margin:-25px 0 0 -25px;
}
Please test.
Any questions let me know.
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