盒子水平和垂直居中

盒子水平和垂直居中

垂直居中的常用三种方法

定义容器

<div class="box1">
	<div class="box2"></div>
</div>
  • 先让子盒子的上边缘与父盒子的水平位置重叠,再将子盒子往上移动自身的一半
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
	position: relative;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
	position: absolute;
	top: 150px; /* 子盒子上边距移动到父盒子的中心位置*/
	margin-top: -51px; /* 子盒子往上移动自身盒子的一半,自身高度+边框 */
}
  • 使用表格的vertical-align:middle实现盒子的垂直居中
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
	display: table-cell; /* 以表格形式展现内容 */
	vertical-align: middle;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
}
  • 使用margin计算盒子的上下边距实现垂直居中
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
	margin-top: 99px; /* (父盒子的高度-子盒子的高度) / 2 */
}

实现效果
在这里插入图片描述

水平居中的常用方法四种方法

定义容器

<div class="box1">
	<div class="box2"></div>
</div>
  • 使用margin: 0 auto
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
	margin: 0 auto;
}
  • 使用margin左右边距
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
	margin-left: 99px; /* (父盒子的宽度-子盒子的宽度) / 2 */
}
  • 先让子盒子左边缘与父盒子中心点重叠,再把子盒子往左移自身一半的宽度
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
	position: relative;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
	position: absolute;
	left: 150px; /* 子盒子左边距移动到父盒子的中心位置*/
	margin-left: -51px; /* 子盒子往左移动自身盒子的一半,自身宽度+边框 */
}
  • 把盒子转换成行内块,然后使用text-align属性使盒子水平居中
.box1 {
	width: 300px;
	height: 300px;
	border: 1px solid blue;
	text-align: center;
}
.box2 {
	width: 100px;
	height: 100px;
	border: 1px solid red;
	display: inline-block; /* 设置子盒子为行内块 */
}

实现效果
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值