+ 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: ???; }
6 odpowiedzi
+ 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 )
+ 6
https://www.sololearn.com/discuss/286789/?ref=app
You can refer this post.
+ 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;
}
+ 1
try : marging: 0 auto; (For it to work, your block element needs a width and a height tho)
+ 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;
}
+ 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.