Solution 1: Position Absolute position +margin negative value

  • Applicable: Child elements have width and height dimensions
  • Method: The parent element is positioned relative to the child element, the child element is positioned absolute, left and top are positioned 50% to the parent element, and margin is used to move half of the child element’s size to the left and up.
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		position: relative;
}
.content{
		background: #FFB90F;
		width: 200px;
		height:200px;
		position: absolute;
		left: 50%;
		top:50%;
		margin: -100px 0 0 -100px;
}
Copy the code

Effect:

Solution 2: Position Absolute position + Transform Adjust position

  • Applicable to: unknown width and height of child elements (of course, you can also know!)
  • Margin (-50%, -50%) margin (-50%, -50%)
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		position: relative;
	}
.content{
		background: #FFB90F;
		/*width: 200px; * /
		/*height:200px; * /
		position: absolute;
		left: 50%;
		top:50%;
		transform: translate(-50%, -50%);
}
Copy the code

Effect:

Scheme 3: Position absolute position + Margin: Auto

  • Applicable: Child elements have width and height dimensions
  • Margin: auto; left, right, top, bottom set to 0; margin: auto
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		position: relative;
	}
.content{
		background: #FFB90F;
		width: 200px;
		height:200px;
		position: absolute;
		left: 0;
		right:0;
		top:0;
		bottom:0;
		margin:auto;
}
Copy the code

Effect: Same as plan 1.

Solution 4: Flex elastic box

  • Applicable to: unknown width and height of child elements (of course, you can also know!)
  • Method: Set the parent element to the elastic box, and center both precy-content and align-items.
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		display: flex;
		justify-content: center;/* The main axis is centered */
		align-items:center;/* The side axis is centered */
	}
.content{
		background: #FFB90F;
		/*width: 200px; * /
		/*height:200px; * /
}
Copy the code

Effect: Same as plan two.