没有固定宽高的盒子的垂直居中

HTML

<div class="box">
<div class="wrapper">我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。我不知道我的宽度和高是多少,我要实现水平垂直居中。</div>
</div>

方案1、Transforms 变形

这是最简单的方法,不仅能实现绝对居中同样的效果,也支持联合可变高度方式使用。内容块定义transform: translate(-50%,-50%)  必须加上

top: 50%; left: 50%;

兼容ie9以及以上的浏览器

毕竟transform只兼容

Internet Explorer 10、Firefox、Opera 

Internet Explorer 9 支持替代的 -ms-transform 属性(仅适用于 2D 转换)

Safari 和 Chrome 支持替代的 -webkit-transform 属性(3D 和 2D 转换)。

Opera 只支持 2D 转换。

CSS

.box{
	 600px;
	height: 600px;
	background: yellow;
	position: relative;
}
.wrapper {
        padding: 20px;
        background: orange;
        color: #fff;
        position: absolute;
        top: 50%;
        left: 50%;
        border-radius: 5px;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%); 为了ie9的兼容性
        transform: translate(-50%, -50%);
}

方案二2、在父级元素上面加上3句话,就可以实现子元素水平垂直居中。

justify-content: center; 子元素水平居中
align-items: center; 子元素垂直居中
display: -webkit-flex;

兼容性方面,ie全部爆炸。相对还是比较适宜于手机端

.box{
	 600px;
	height: 600px;
	background: yellow;
	justify-content: center;   
	align-items: center;      
	display: -webkit-flex;
}
.wrapper {
	background: orange;
	color: #fff;
	 320px;
}

原文链接:https://www.cnblogs.com/xuemingyao/p/5829263.html

原文地址:https://www.cnblogs.com/liyouwu/p/9009533.html