+ 1

How to center a block element vertically and horizontally inside another block element?

The idea is to center the child block horizontally and vertically using a simple code. HTML: <div id="padre"> <div id="hijo"> </div> </div> CSS: #padre { width: 300px; height: 300px; position: ???; display: ???; } #hijo { width: 100px; height: 100px; position: ???; display: ???; }

10th Apr 2017, 4:06 PM
Samir Quiceno Bermudez
Samir Quiceno Bermudez - avatar
6 Respostas
+ 6
Your example is working... as well as 'centered' is expected 'horizontally' ^^ Are you expecting a vertical centering? With your actual CSS, simplest way is to change: margin:0 auto; ... to: margin:50px; ^^ ( else, vertical auto centering is quite hard to obtain :P )
10th Apr 2017, 4:15 AM
visph
visph - avatar
10th Apr 2017, 4:21 PM
Ashwani Kumar
Ashwani Kumar - avatar
+ 3
thanks @Ashwani Kumar! That post that references has a lot to do, and, finally, I found the answer; Response that has to do with the Flexbox functions completely. HTML: <body> <div id="padre"> <div id="hijo"></div> </div> </body> CSS: #padre { width:300px; height:300px; background-color:royalblue; /* flexbox */ display:flex; justify-content: center; align-items: center; } #hijo { width:100px; height:100px; display:flex; background-color:red; }
11th Apr 2017, 6:23 AM
Samir Quiceno Bermudez
Samir Quiceno Bermudez - avatar
+ 1
try : marging: 0 auto; (For it to work, your block element needs a width and a height tho)
9th Apr 2017, 9:15 PM
CHMD
CHMD - avatar
+ 1
it does not work. HTML: <!DOCTYPE html> <html> <head> <title>Doc</title> <link rel="stylesheet" href="xxx.css"> </head> <body> <div id="padre"> <div id="hijo"> </div> </div> </body> </html> CSS: #padre { width: 400px; height: 400px; background-color: red; } #hijo{ width: 200px; height: 200px; background-color: white; margin:0 auto; }
10th Apr 2017, 2:43 AM
Samir Quiceno Bermudez
Samir Quiceno Bermudez - avatar
+ 1
@visph, What you say is true, only centered horizontally, however, I do not share the idea that vertically centering is complex, but neither do I have the solution of the problem.
10th Apr 2017, 3:02 PM
Samir Quiceno Bermudez
Samir Quiceno Bermudez - avatar