<div class="container">
<div class="element">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in lectus quam.</p>
<p>Praesent eget erat ut risus sodales ornare. Quisque quis pretium metus.</p>
</div>
</div>
* {
/* establece que el tamaño de
la caja sera desde los bordes*/
box-sizing: border-box;
}
body {
/* quita los margenes del body */
margin: 0;
background-color: aqua;
}
.container {
position: relative;
/* calcula el ancho del vh - el tamaño de la caja */
/* se puede usar /2 para que no crezca el vh */
margin: calc((100vh - 450px) /2) auto;
width: 450px;
height: 450px;
background-color: rgba(245, 245, 245, 0.5);
}
.box {
width: 150px;
height: 150px;
background-color: rgba(25, 25, 25, 0.5);
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
* {
/* establece que el tamaño de
la caja sera desde los bordes*/
box-sizing: border-box;
}
body {
/* quita los magenes de las cajas*/
margin: 0;
background-color: aqua;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container{
display: flex;
width: 450px;
height: 450px;
align-items: center;
justify-content: center;
background-color: rgba(245, 245, 245, 0.5);
}
.box{
/* el hijo es bueno y obedece al padre :)*/
width: 150px;
height: 150px;
background-color: rgba(25, 25, 25, 0.5);
}
.centrarVerticalmente{
position: absolute;
height: 100px;
background: red;
top: 50%;
margin-top: -50px; /*mitad de la altura del div*/
}
.centrarVerticalmente2{
height: 50px;
background: yellow;
position: absolute;
top: 50%;
transform: translatey(-50%);
}
<!-- en caso que ya tengas un transform sobre el eje x -->
<div class="centrarVerticalmente">
Div centrado verticalmente
</div>
<!-- en caso que no tengas un transform en el eje x -->
<div class="centrarVerticalmente2">
Div centrado verticalmente
</div>
方法有千百种:
线高法
示例:垂直对齐的文本。
结果:
CSS 表格方法
例子:
结果:
绝对定位和拉伸
例子:
结果:
浮动Div(浮动Div)
例子:
结果:
我从这个链接得到了例子。还有几个。
您可以使用伪元素:before + vertical-align:middle
有两种非常简单的方法
你可以使用弹性
在这里,我留给您 2 个选项,这是我使用的选项:
在我看来,第二个选项是最好的,虽然它已经有了答案,但它可能对你有用。