CSS div居中

所有css

body{
	background-color: honeydew;
}
  • 1、absolute + 负margin
	<div class="father1">
		<div class="method1">
		</div>
	</div>
.father1{
	width: 500px;
	height: 500px;
	background-color: brown;
	position: relative;    /* 父元素相对定位,否则子元素相对再往上层找的定位元素居中 */
}
.method1{
	width: 200px;    /* 宽高固定 */
	height: 100px;
	position: absolute;
	top: 50%;    /* 绝对定位,左上角在正中间 */
	left: 50%;
	margin-left: -100px;    /* 各取负一半的margin */
	margin-top: -50px;
	background-color: bisque;
}


  • 2、absolute + margin auto
.father2{
	width: 500px;
	height: 500px;
	background-color: brown;
	position: relative;
}
.method2{
	width: 200px;
	height: 100px;
	background-color: bisque;
	position: absolute;  /* 绝对定位,上下左右0,margin自动auto */
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	margin: auto;
}

html结构同1,效果图同1


  • 3、absolute + calc
.method3{
	width: 200px;
	height: 100px;
	background-color: bisque; /*  */
	position: absolute;    /* 绝对定位,位置利用cala动态计算 */
	top: calc(50% - 50px);
	left: calc(50% - 100px);
}

html结构同1,效果图同1,father3与father1样式相同


  • 4、absolute + tramsform
.method4{
	width: 200px;
	height: 100px;
	background-color: bisque; /*  */
	position: absolute;    /* 绝对定位,transform移动位置到正中间 */
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

html结构同1,效果图同1,father3与father1样式相同


  • 5、line-height + text-align + inline-block + vertial-align
.father5{
	background-color: brown;
	line-height: 300px;
	text-align: center;    /* 水平居中 */
}
.method5{
	width: 200px;
	height: 100px;
	background-color: bisque; /*  */
	display: inline-block;
	vertical-align: middle;    /* 垂直居中 */
	line-height: initial;
	text-align: left; /* 修正文字 */
}

html结构同1

  • 6、table-cell
.father6{
	display: table-cell;    /* table布局,水平垂直居中 */
	text-align: center;
	vertical-align: middle;
	background-color: brown;
	width: 500px;
	height: 500px;
}
.method6{
	width: 200px;
	height: 100px;
	background-color: bisque; /*  */
	display: inline-block;
}

html结构同1,效果图同1


  • 7、flex
.father7{
	display: flex;    /* flex弹性布局,利用下面两个属性居中 */
	justify-content: center;
	align-items: center;
	background-color: brown;
	width: 500px;
	height: 500px;
}
.method7{
	width: 200px;
	height: 100px;
	background-color: bisque; /*  */
}

html结构同1,效果图同1


  • 8、grid
.father8{
	display: grid;    /* 栅格布局 */
	background-color: brown;
	width: 500px;
	height: 500px;
}
.method8{
	align-self: center;    /* 栅格布局,子元素设置水平垂直居中 */
	justify-self: center;
	width: 200px;
	height: 100px;
	background-color: bisque; /*  */
}

html结构同1,效果图同1

参考链接:http://jiazq.xyz/view/117

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值