CSS - How to center nested divs?

New in CSS.

I am trying to center nested divs using the code below

HTML

<html> <head> <title>My website</title> <link rel="stylesheet" type="text/css" href="css/main.css" /> </head> <body> <div id="wrapper"> <div id="formpanel"> <div id="loginForm"> </div> </div> </div> </body> </html> 

CSS

 body { margin: 0; background : #90ADB7 url('images/background.png') repeat-x; font-family: verdana, sans-serif; font-size: 0.85em; } #wrapper { width: 960px; margin: 0 auto; border-style:solid; padding: 190px 0; } #formpanel { width: 400px; height: 400px; background-color: yellow; margin: auto; } #loginForm { margin: auto; width: 50%; height: 50%; background-color:blue; } 

the problem is that the innermost div (#loginForm) is reset with the top edge of the outer div (#formpanel). How do I center the inner div?

Screenshot enter image description here

+6
source share
4 answers

You can use relative positioning:

http://jsfiddle.net/a879W/

+5
source
 #formpanel { position: relative; ... } #loginForm { position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; width: 200px; height: 200px; background-color:blue; } 
+2
source
 #loginForm { position:absolute; top:25%; margin: auto; width: 50%; height: 50%; background-color:blue; } 

EDIT: top: 25% not 50%.

+1
source

You can use absolute positioning:

 #formpanel { width: 400px; height: 400px; background-color: yellow; margin: auto; position:relative; } #loginForm { position: absolute; width: 200px; height:200px; left: 100px; top: 100px; background-color:blue; } 
0
source

Source: https://habr.com/ru/post/903298/


All Articles