How could I vertically center a child within a parent ?
And, the width and height of child and parent is fixed, but unknown.
How could I realize it?
<div class="parent">
<div class="child"></div>
</div>
How could I vertically center a child within a parent ?
And, the width and height of child and parent is fixed, but unknown.
How could I realize it?
<div class="parent">
<div class="child"></div>
</div>
in css vertical-align:middle
is used to align a child vertically centre. But this property is applied to only those elements which havedisplay:inline-block
or display:table-cell
. So accordingly try to apply display
property and you will get vertically centre position of your elements.
My prefered technique for centering a box both vertically and horizontally requires two containers.
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
text-align: left;
or text-align: right;
, unless you want text to be centeredThe elegance of this technique, is that you can add your content to the content box without worrying about its height or width!
Just add your content to the content box.
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
<p>You can put anything here</p>
<p>Yes, really anything!</p>
</div>
</div>
</div>
See also this Fiddle!
Try this code
body {
margin: 0;
padding:0;
}
.div1 {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.div2 {
width: 50vw;
height: 50vh;
background: #999;
}