面试必问之CSS水平垂直居中

水平居中:

① margin:0 auto;

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<style> 
	body{margin: 0;}
	.outer{
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		text-align:center;
	}	
	.inner{
		width:300px;
		height:300px;
		background-color:#5cb85c;
		display:inline-block;
	}
</style>
</head>
<body>	
  <div class="outer">
	<div class="inner">	
	</div>
  </div>	

</body>
</html>

② text-align: center;

.outer{
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		text-align:center;
	}
.inner{
		width:300px;
		height:300px;
		background-color:#5cb85c;
		display:inline-block;
	}

水平垂直居中:

① 父元素:display:flex; 弹性布局
子元素:align-self:center;设置单个子元素在纵轴上的排列

.outer{		
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		display:flex;
	}
	
.inner{
		margin:0 auto;//水平居中
		width:300px;
		height:300px;
		background-color:#5cb85c;
		align-self:center;//垂直居中		
	}

② display:flex;弹性布局
justify-content: center;设置元素在横轴上的排列
align-items: center;设置元素在纵轴上的排列

.outer{
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		display:flex;
        justify-content: center;//水平居中
		align-items: center;垂直居中
	}
	
.inner{
		width:300px;
		height:300px;
		background-color:#5cb85c;	
	}

③ 绝对定位和transform

.outer{
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		position:relative;
	}
	
.inner{
		width:300px;
		height:300px;
		background-color:#5cb85c;
	    position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);//移动
	}

④ 绝对定位,并且margin值位auto 此方法不受元素宽高限制

.outer{
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		position: relative;
	}
	
.inner{
		width:400px;
		height:200px;
		background-color:#5cb85c;		
		position: absolute;
		margin: auto;
		left: 0;
	    right: 0;
	    bottom: 0;
	    top:0;
	}

⑤ table-cell属性将元素换成表格样式,再利用表格居中

.outer{
		width:600px;
		height:600px;
		background-color:#D0D0D0;
		display: table-cell;
	    vertical-align: middle;
	}
	
.inner{
		margin:0 auto;
		width:300px;
		height:300px;
		background-color:#5cb85c;		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值