如何将html盒子中的文字居中

请问一下如何将html盒子中的文字居中?应该用什么方法?什么方法比较简单?

img

img

要垂直居中p的 line-height 设置成与 height 一样就可以了

p:nth-child(1){
    height: 10rem;
    line-height: 10rem;
}
p:nth-child(2){
    height: 4rem;
    line-height: 4rem;
}

用display:flex;

div{
    display: flex;
    align-items: center;
    justify-content: center;
}

给你的p元素加上这个样式


text-align:center;

如果要垂直居中

line-height:300px;

center标签

我是居中的

将一行文字设为垂直居中的话,设置其行高等于父元素高度就行。

p标签加样式:

p{
    display: flex;
    align-items: center;
    justify-content: center;
}

1.使用 Flex 只需要在父盒子设置:display: flex; justify-content: center;align-items: center;
2.使用 CSS3 transform 父盒子设置:position:relative Div 设置: transform: translate(-50%,-50%);position: absolute;top: 50%;left: 50%;
3. 父元素有高度的情况下并且只有一个 div 子元素 position:absolute; margin:auto; top:0; right:0; bottom:0; left:0;
望采纳谢谢

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632