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>

Demo

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>

Demo

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>

Demo


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>

Demo

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>

Demo

We also can set display block for inline tag and do same as block inside block.

Only inline

Just use vertical-align: middle; for all child items.

Demo