CSS: Align center - vertical and horizontal
Box in box
Know child's height and width:
<style type="text/css">
#parent{
width: 100px;
height: 100px;
border: 1px solid red;
position: relative;
}
#child{
width: 20px;
height: 20px;
border: 1px solid blue;
position: absolute;
top: 50%;
margin-top: -11px; /* height / 2 + border-width */
left: 50%;
margin-left: -11px; /* width / 2 + border-width */
}
</style>
<div id="parent">
<div id="child">
</div>
</div>
Know only child's height:
<style type="text/css">
#parent{
width: 100px;
height: 100px;
border: 1px solid red;
position: relative;
}
#child{
width: 20px;
height: 20px;
border: 1px solid blue;
margin: auto;
position: relative;
top: 50%;
margin-top: -11px; /* height / 2 + border-width */
}
</style>
<div id="parent">
<div id="child">
</div>
</div>
Don't know child's height:
<style type="text/css">
#parent{
width: 100px;
height: 100px;
border: 1px solid red;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
#child{
width: 20px;
height: 20px;
border: 1px solid blue;
}
</style>
<div id="parent">
<div id="child">
</div>
</div>
Inline in box
Inline have only one line
<style type="text/css">
#parent{
width: 200px;
height: 100px;
border: 1px solid red;
text-align: center;
}
#child{
line-height: 100px; /* same as parent's height */
}
</style>
<div id="parent">
<span id="child">This is test</span>
</div>
Inline have multi line
<style type="text/css">
#parent{
width: 200px;
height: 100px;
border: 1px solid red;
text-align: center;
display: table;
}
#child{
display: table-cell;
vertical-align: middle;
}
</style>
<div id="parent">
<span id="child">This is test This is test This is test This is test</span>
</div>
We also can set display block for inline tag and do same as block inside block.
Only inline
Just usevertical-align: middle; for all child items.