css 水平垂直居中

内联块元素方法display: inline-block

.parent
	.child
.parent
	width: 100px
	height: 100px
	border: 1px solid red
	text-align: center // 水平居中
	font-size: 0
	&::after
		content: ''
		display: inline-block
		vertical-align: middle
		width: 0
		height: 100%
.child
	display: inline-block
	vertical-align: middle
	width: 50px
	height: 50px
	border: 1px solid blue

!> 可能会在水平方向会有一定的偏移量,《css世界》里面提到‘幽灵节点’,给父容器加了一个font-size:0 解决

表格元素方法dispaly: table-cell

.parent
	.child
.parent
	width: 100px
	height: 100px
	border: 1px solid red
	font-size: 0
	display: table-cell
	vertical-align: middle
.child
	width: 50px
	height: 50px
	border: 1px solid blue
	margin: 0 auto

相对定位position: absolute

.parent
	.child
.parent
	width: 100px
	height: 100px
	border: 1px solid red
	position: relative
.child
	width: 50px
	height: 50px
	border: 1px solid blue
	position: absolute
	top: 0
	bottom: 0
	left: 0
	right: 0
	margin: auto

相对定位position + transform

.parent
	.child
.parent
	width: 100px
	height: 100px
	border: 1px solid red
	position: relative
.child
	width: 50px
	height: 50px
	border: 1px solid blue
	position: absolute
	top: 50%
	left: 50%
	transform: translate(-50%, -50%)

flex布局

.parent
	.child
.parent
	width: 100px
	height: 100px
	border: 1px solid red
	display: flex
	justify-content: center
	align-items: center
.child
	width: 50px
	height: 50px
	border: 1px solid blue

flex + margin

.parent
	.child
.parent
    width: 100px
    height: 100px
    border: 1px solid red
    display: flex
.child
    width: 50px
    height: 50px
    border: 1px solid blue
    margin: auto

grid布局

.parent
	.child
.parent
	width: 100px
	height: 100px
	border: 1px solid red
	display: grid
.child
	width: 50px
	height: 50px
	border: 1px solid blue
	margin: auto
posted @ 2019-06-05 19:40  fanlinqiang  阅读(363)  评论(0编辑  收藏  举报