Method that centers an element in both the vertical and horizontal directions of its parent

Without further ado, get right to the code

The HTML code is as follows:

Copy it to the <body></body> tag in your ***.html directory

<div class="wrap">
	<div class="inner">
	
	</div>
</div>
Copy the code

Here is the CSS code:

Copy this code to

in your ***.html directory, or import an external style sheet and place it in your ***.css file.

  1. Positioning method (1)
.wrap{
	width: 300px;
    height: 300px;
    background: yellow;/* Add color to see the interface */
    position: relative;
}
.inner{
  	width: 40px;
   	height: 40px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin:auto;
    background: orange;/* Add color to see the interface */
 }
Copy the code
  1. Positioning method (2)

    .wrap{
        width: 300px;
        height: 300px;
        position: relative;
        background: yellow;/* Add color to see the interface */
    }
    .inner{
        width: 40px;
        height: 40px;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -20px;
        margin-top: -20px;
        background: orange;/* Add color to see the interface */
    }
    Copy the code
  2. Change the display of parent and child elements (not recommended)

	.wrap{
        width: 300px;
        height: 300px;
        display: table-cell;
        text-align: center;
        vertical-align: middle;
        background: yellow;/* Add color to see the interface */
    }
    .inner{
        width: 40px;
        height: 40px;
        display: inline-block;
        background: orange;/* Add color to see the interface */
    }
Copy the code
  1. Css3 elastic box method
	.wrap{
        width: 300px;
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: yellow;
    }
    .inner{
        width: 40px;
        height: 40px;
        background: orange;
    }
Copy the code

The display: Flex attribute is not compatible with the red version of the browser.



The renderings of the above four methods on the browser are as follows:

If you know any other ways, please leave a comment to me. I would be very grateful, and I can help other friends who read my blog. Thank you!