One, horizontal center

HTML code with only parent and child elements

<div class="parent">
    <div class="son"></div>
</div>
Copy the code
  • The first method is to add in the style of the child elementmargin: 0 auto;
  • The second method uses localization

    Parent element relative positioningposition: relative;

    The child element is absolutely positioned
position: absolute;
top: 0;
left: 50%;
margin-left: -50px;
Copy the code
  • The third method, flex layout, adds the parent element
display: flex;
justify-content: center;
Copy the code

Two, horizontal and vertical center

  • Using the positioning

    Parent element relative positioningposition: relative;

    The child element is absolutely positioned
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
Copy the code
  • Using Flex layout

Add to the parent element

display: flex;
justify-content: center;
align-items: center;
Copy the code