方法一:利用line-height与text-align
1)css部分
<style> .box { height: 100px; color:#fff; background-color: lightskyblue; text-align: center; line-height: 100px; vertical-align: middle; } </style>
2)html部分
<div class="box"> <span>hello world</span> </div>
3)效果展示
方法二:利用vertical-align和text-align
原理:给class为box的div追加一个子元素,让其高度与父元素高度相同,通过vertical-align使其与文本的1/2处对齐。
1)css部分
<style> .box { height: 100px; color:#fff; background-color: lightseagreen; text-align: center; /* line-height: 100px; */ /* vertical-align: middle; */ } .box::after{ content: ''; display: inline-block; height: 100px; vertical-align: middle; } </style>
2)html部分
<div class="box"> <span>hello world</span> </div>
3)效果展示