The son div can be put in the center with real number in margin.
div.father {
height: 330px;
width: 330px;
border: 1px solid black;
}
div.son {
margin:114px 114px 114px 114px;
border: 1px solid black;
height: 100px;
width: 100px;
}
<div class="father">
<div class="son"></div>
</div>
The son div can be put in the center.
Maybe there is another smart way instead of margin:114px 114px 114px 114px;
,if the border width was changed ,then the margin number will be changed accordingly,how to fix it?
one way by which you can achieve this is by settting parent display:table-cell;vertical-align:middle;
and for son margin:auto
div.father {
height: 330px;
width: 330px;
border: 1px solid black;
display:table-cell;
vertical-align:middle;
}
div.son {
margin:auto;
border: 1px solid black;
height: 100px;
width: 100px;
}
<div class="father">
<div class="son"></div>
</div>
The flexbox
module seems a smart and modern candidate for this task
justify-content
aligns the item along the main axis (horizontally) and align-items
aligns the item along the cross-axis (vertically)
div.father {
height: 330px;
width: 330px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid black;
}
div.son {
border: 1px solid black;
height: 100px;
width: 100px;
}
Codepen demo and browser support (IE10+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With