css垂直水平居中的方法总结

垂直水平居中

**情况一:**元素宽高未知

方法一:定位

	.box {
		width: 500px;
		height: 500px;
		border: 1px solid red;
		position: relative;
	}
	.content {
		width: 100px;
		height: 100px;
		background: green;
		position: absolute;
		top: 50%;
		left: 50%; //相对于父元素的50%
		transform: translate(-50%,-50%);  //相对于自身的50%
	}

方法二:弹性布局(高度已知也可用)

	.box {
		width: 500px;
		height: 500px;
		border: 1px solid red;
		display: flex;
		justify-content: center;
		align-items:center;
	}
	.content {
		width: 100px;
		height: 100px;
		background: green;
	}

情况二:高度已知
方法一:使用定位

	.box {
		width: 500px;
		height: 500px;
		border: 1px solid red;
		position: relative;
	}
	.content {
		width: 100px;
		height: 100px;
		background: green;
		position: absolute;
		top: 50%;
		left: 50%;
		margin: -50px 0 0 -50px;
	}

方法二:

.box {
		width: 500px;
		height: 500px;
		border: 1px solid red;
		position: relative;
	}
	.content {
		width: 100px;
		height: 100px;
		background: green;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		margin: auto;
	}

上图如下在这里插入图片描述

水平居中

情况一:有宽高,子元素为块级元素

.box {
		width: 300px;
		height: 300px;
		border: 1px solid red;
	}
	.content {
		width: 100px;
		height: 100px;
		background: skyblue;
		margin: 0 auto;
	}

情况二:无宽高,元素为行非块级元素

	.box {
		width: 300px;
		height: 300px;
		border: 1px solid red;
		text-align: center;
	}
	.content {
		background: skyblue;
	}

在这里插入图片描述

垂直居中

情况一:块级元素

方法一:

	.box {
		width: 500px;
		height: 500px;
		border: 1px solid red;
		position: relative;
	}
	.content {
		width: 100px;
		height: 100px;
		background: green;
		position: absolute;
		top: 50%;
		left: 50%;
		margin: -50px 0 0 -50px;//或者transform:translate(-50%,-50%)
	}

方法二:

```
.box {
	width: 500px;
	height: 500px;
	border: 1px solid red;
	display: flex;
	align-items:center;
}
.content {
	background: green;
}*/
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191105111700321.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMzM5OTc1,size_16,color_FFFFFF,t_70)

情况二:非块级元素

	.box {
		width: 500px;
		height: 500px;
		border: 1px solid red;
	}
	.content {
		background: green;
		line-height: 500px;
	}*/
</style>
<body>
	<div class="box">
		<span class="content">我是垂直居中哦</span>
	</div>
</body>

在这里插入图片描述

	.box {
		width: 200px;
		height: 200px;
		border: 1px solid red;
		vertical-align: middle;
        display: table-cell;
	}
	.content {
		background: green;
	}*/
</style>
<body>
	<div class="box">
		<span class="content">我是垂直居中哦噢噢噢噢哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦</span>
	</div>
</body>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值