DIV内容居中

 

 

DIV内容居中_第1张图片

1.flex布局实现

css代码

.box{
	width: 200px;
	height: 200px;
	display: flex;
	display: -webkit-flex;
	justify-content: center;
	align-items: center;
	background: #AAA;
}
.inner{
	width: 100px;
	height: 100px;
	background:darkcyan;
}

html代码

2.position (元素已知宽度)

父元素设置为:position: relative;

子元素设置为:position: absolute;

距上50%,据左50%,然后减去元素自身宽度的一半距离就可以实现

css代码

.box{
	width: 200px;
	height: 200px;
	position: relative;
	background: #AAA;
}
.inner{
	width: 100px;
	height: 100px;
	position: absolute;
	left: 50%;
	top: 50%;
	margin: -50px 0 0 -50px;
	background:darkcyan;
}

html代码

3.  position transform (元素未知宽度)

如果元素未知宽度,只需将上面例子中的 margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);

CSS代码

.box{
	width: 200px;
	height: 200px;
	position: relative;
	background: #AAA;
}
.inner{
	width: 100px;
	height: 100px;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	background:darkcyan;
}

html代码

4. position(元素已知宽度)(left,right,top,bottom为0,maigin:auto )

css代码

.box{
	width: 200px;
	height: 200px;
	position: relative;
	background: #AAA;
}
.inner{
	width: 100px;
	height: 100px;
	position: absolute;
	left: 0;
	top: 0;
	bottom: 0;
	right: 0;
	margin: auto;
	background:darkcyan;
}

html代码

 

你可能感兴趣的:(JavaScript)