First, the basic structure style

<body>    <div class="box">        <span></span>    </div></body>
Copy the code

Center the span element horizontally and vertically with its parent div element

The result is as follows:

Here are three commonly used methods:

1. The positioning

<style> * { margin: 0; padding: 0; } .box { width: 100px; height: 100px; background: #f40; position: relative; margin: 200px auto; } .box span{ width: 20px; height: 20px; background: pink; border-radius: 50%; position: absolute; left: 50%; margin-left: -10px; You can also write transition:translateX(-50%); top:50%; margin-top: -10px; The transition: translateY (50%); } </style>Copy the code

There’s another kind of positioning

.box span{ position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; }Copy the code

2. Flex sets spindle and side axis to center

<style>        * {            margin: 0;            padding: 0;        }        .box {            width: 100px;            height: 100px;            background: #f40;            margin: 200px auto;            display: flex;            justify-content: center;            align-items: center;        }        .box span{            width: 20px;            height: 20px;            background: pink;            border-radius: 50%;        }    </style>
Copy the code

3. Simplest, most direct, most awesome

Margin: auto; Can be
<style>        * {            margin: 0;            padding: 0;        }        .box {            width: 100px;            height: 100px;            background: #f40;            margin: 200px auto;            display: flex;        }        .box span{            width: 20px;            height: 20px;            background: pink;            border-radius: 50%;            margin: auto;        }    </style>
Copy the code

Conclusion:

The above three methods are often used in our actual scenarios, so we need to master them.
And I personally recommend using the latter two, not the first one, the latter two are simple, use Flex layout, avoid positioning.