css面试题实现元素垂直水平居中-包括未知宽高的元素五种回答

css实现元素垂直水平居中-包括未知宽高的元素

这个一道很经典的面试题,做项目中也常会出现这样的需求。 现在我就用几种比较常用的方法。兼容性也列出来。

第一种已知宽高(定位加负边距解决)兼容到IE6

position: absolute;
z-index: 8;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
background: red;
复制代码

demo地址 JSBin

第二种未知宽高 (定位加margin解决) 兼容到IE8 移动端推荐使用

position: absolute;
z-index: 8;
left: 0;
top: 0;
bottom: 0;
right: 0;
width: 200px;
height: 200px;
margin: auto;
background: red;
复制代码

如果改变宽度和高度还是垂直水平居中的。 demo地址 JSBin

第三种未知宽高 (定位加transform解决) 兼容到IE9 移动端推荐使用

position: absolute;
z-index: 8;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
transform: translate(-50%, -50%);
background: red;
复制代码

如果改变宽度和高度还是垂直水平居中的。 demo地址 JSBin

第四种未知宽高 (弹性盒子模型解决) 兼容到IE10

display: flex;
display: -webkit-flex;
align-items:center;
justify-content: center;
复制代码

如果改变宽度和高度还是垂直水平居中的。 demo地址 JSBin

第五种未知宽高 (table特性解决的) 兼容到IE6 PC端推荐使用

#box{
    width: 100px;
	height:100px;
	text-align:center;
	font-size:0;
    background: red
}
#box:after,#box span{
	display:inline-block;
	*display:inline;
	*zoom:1;
	width:0;
	height:100%;
	vertical-align:middle;
}
#box:after{
	content:'';
}
#box p{
	display:inline-block;
	*display:inline;
	*zoom:1;
	vertical-align:middle;
	font-size:16px;
}
复制代码

demo地址 JSBin

我的博客和GitHub地址喜欢的话送个star谢谢。

github.com/lanpangzhi

blog.langpz.com

参考

demo.doyoe.com/css/alignme…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值