Din*_*ina 16 html css text-align
如何将文本水平和垂直居中?我不想使用绝对位置因为我尝试使用它而我的其他div变得更糟.还有另一种方法吗?
div {
height: 400px;
width: 800px;
background: red;
}Run Code Online (Sandbox Code Playgroud)
<div>
<h1>This is title</h1>
</div>
Run Code Online (Sandbox Code Playgroud)
elr*_*eda 11
你可以使用display flex它为所有直接子节点启用flex上下文,并且flex方向建立主轴,从而定义flex项放置在flex容器中的方向
div{
height: 400px;
width: 800px;
background: red;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
只需这样做,它适用于每个浏览器:
div{
height: 400px;
width: 800px;
background: red;
line-height: 400px;
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
该line-height属性指定行高(垂直居中),text-align:center并将其直接放置在水平居中。