未知盒子宽高使盒子垂直水平居中

Posted linxim

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了未知盒子宽高使盒子垂直水平居中相关的知识,希望对你有一定的参考价值。

???注意:未知盒子宽高并不是盒子没有宽高,是不知道盒子宽高的具体值是多少。

垂直水平居中方法(transform:translate)

让我垂直水平居中

.parent{
position: relative;
width: 100px;
height: 100px;
border: 1px solid #ccc;
}

.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: #ddd;
}

 

垂直水平居中方法(弹性布局)

让我垂直水平居中

.parent1{
display: flex;
justify-content: center;
align-items:center;
width: 200px;
height: 100px;
border: 1px solid #ccc;
}

.child1{
background: #ddd;
width: 100px;
height: 50px;
}

 

垂直水平居中方法(网格布局)

让我垂直水平居中

.parent2{
display: grid;
/* 在行中对齐方式 */
justify-items:center;
/* 在列中的对齐方式 */
align-items:center;
width: 200px;
height: 100px;
border: 1px solid #ccc;
}

.child2{ width: 100px;
height: 50px;
background: #ddd;
}

 

垂直水平居中方法(定位)

让我垂直水平居中

.parent3{ width:300px;
height: 100px;
position: relative;
border: 1px solid #ccc;
}

.child3{
width: 100px;
height: 50px;
position:absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: #ddd;
}

以上是关于未知盒子宽高使盒子垂直水平居中的主要内容,如果未能解决你的问题,请参考以下文章

盒子在浏览器中水平垂直居中

div盒子水平居垂直中的几种方法

如何使文字在div中水平和垂直居中的css代码

模态框中水平垂直居的问题

实现没有宽高的盒子水平垂直居中

div盒子水平垂直居中的方法推荐