Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart way to put div center instead of real number?

Tags:

html

css

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. enter image description here

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?

like image 392
showkey Avatar asked Dec 11 '22 18:12

showkey


2 Answers

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>
like image 101
Pavan Teja Avatar answered Dec 30 '22 16:12

Pavan Teja


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+)

like image 26
Fabrizio Calderan Avatar answered Dec 30 '22 18:12

Fabrizio Calderan