Horizontal and vertical center layout


Meaning: centered both horizontally and vertically

1. Use table-cell to make the table content alignment middle to achieve vertical centering; and then take different methods to achieve horizontal centering depending on whether it is in-line elements or block-level content.

#parent{
    
    
	display:table-cell;
	vertical-align:middle;
	/*text-align:center;*//*如果是行内内容用这个*/
}
#child{
    
    
	display:table;
	/*margin:0 auto;*/ /*如果是块级元素添加这个*/
	}

Insert picture description here

2. Positioning

  • Principle: The child’s absolute parent phase, top, right, bottom, and left values ​​are relative to the size of the parent element, margin or transform (transformation, displacement, rotation, scaling, and tilt operations can be performed on the element, support 2D or 3D conversion, IE9+ Support.) is relative to its own size, combined use to achieve the purpose of horizontal game.
#parent{
    
    position:relative;}
    #child{
    
    
		position:absolute;
		top:50%;
		left:50%;
		/*①定宽高时等同于margin-left:负自身宽度一半;margin-top:负自身高度一半;*/
		/*②transform: translate(-50%,-50%);*//*translate:transform(变换)的方法tanslate(位移)*/
	}

Insert picture description here

If you ask as much as possible to achieve horizontal and vertical centered layout, there is another way to solve it:
set the up, down, left, and right to zero and set the margin to auto

#parent{
    
    position:relative;}
    #child{
    
    
		position:absolute;
		top:0;
		bottom:0;
		left:0;
		right:0;
		margin:auto;
		width: 200px;
		height: 200px;
		background: red;
		
	}

3. Use flex to achieve:

Flex will control the arrangement of child elements

#parent{
    
    
		display:flex;
		justify-content:center;//控制水平对齐
		align-items: center;//控制垂直对齐
		}

Guess you like

Origin blog.csdn.net/qq_43218276/article/details/114607391