Smart way to put a div center instead of a real number?

The son of a div can be placed in the center with a real number in the field.

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>
Run codeHide result

A son div can be placed in the center. enter image description here

Maybe there is another smart way instead margin:114px 114px 114px 114px;, if the border width has been changed, then the field number will be changed accordingly, how to fix it?

+4
source share
4 answers

The module flexboxseems like a smart and modern candidate for this task.

justify-contentaligns an element along the main axis (horizontal) and align-itemsaligns the element along the transverse 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 +)

+2

, , - display:table-cell;vertical-align:middle; 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>
Hide result
+7

If the width and height of the div.son remain the same, then the code below will work for you.

div.father {
height: 330px;
width: 330px;
border: 1px solid black;
position:relative;
}

div.son {
position: absolute;
border: 1px solid black;
height: 100px;
width: 100px;
  top:50%;
  left:50%;
  margin: -50px 0 0 -50px; 
}
<div class="father">
<div class="son"></div>
</div>
Run codeHide result
+2
source

There are several ways to achieve centering, depending on the exact requirements.

One example is the positioning of a child absolutely (and the parent is relative), setting the field to automatic and the distance from each side to 0.

div.father {
  border: 1px solid black;
  height: 330px;
  position: relative;
  width: 330px;
}
div.son {
  border: 1px solid black;
  bottom: 0;
  height: 100px;
  left: 0;
  margin: auto;
  position: absolute;
  right: 0;
  top: 0;
  width: 100px;
}
<div class="father">
  <div class="son"></div>
</div>
Run codeHide result

For a complete guide to centering in CSS, I recommend this page . It has a complete guide for each type of centering.

+2
source

All Articles