css水平垂直居中方法

子元素定宽高和不定宽高两种形式

子元素不定宽高

1、子绝父相,transform:translate

.father{
    
    
	position:relative;
}
.child{
    
    
	position:absolute;
	left:50%;
	top:50%;
	transform:translate(-50%,-50%);
}

2、父元素flex布局,justify-content,align-item

.father{
    
    
	display:flex;
	justify-content:center;
	align-items:center;
}

3、父元素table布局,text-align(center)和vertical-align(middle),子元素行内块

.father{
    
    
	display:table-cell;
    text-align:center;
    vertical-align:middle;
}
.child{
    
    
    display:inline-block;
}

子元素定宽高

1、子绝父相,负margin

.father{
    
    
    position:relative;
}
.child{
    
    
    position:absolute;
    left:50%;
    top:50%;
    width:100px;
    height:100px;
    margin-left:-50px;
    margin-top:-50px;
}

2、子绝对+left/right/bottom/top 全部0 ,margin auto

.father{
    
    
    position:relative;
}
.child{
    
    
    position:absolute;
    display:inline;
    width:100px;
    height:100px;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin:auto;
}

3、宫格布局,子元素margin auto

.box{
    
    
	display:grid;
}
.children-box{
    
    
	width:100px;
	height:100px;
	margin:auto;
}

猜你喜欢

转载自blog.csdn.net/m0_61696809/article/details/129353791