Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align centrally and vertically a div element without using javascript

Tags:

css

less

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

like image 577
Lorraine Bernard Avatar asked Mar 07 '26 00:03

Lorraine Bernard


1 Answers

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.

like image 56
Patrick Maciel Avatar answered Mar 09 '26 12:03

Patrick Maciel