如何垂直居中H1内带打字动画的inline-block元素?
解决方案
要实现H1内第二个span垂直居中,同时保持打字动画在居中容器内从左到右展开,只需调整H1的布局逻辑并优化span的动画设置,具体操作如下:
1. 调整H1的布局规则
将H1设置为垂直方向的flex容器,让内部两个span自动水平居中,同时清除默认margin避免多余间距:
#description h1 { display: flex; flex-direction: column; align-items: center; gap: 1rem; /* 可选:给两个span添加垂直间距 */ margin: 0; }
2. 简化第一个span的样式
由于H1已经通过align-items:center实现了内部元素的水平居中,第一个span无需再单独设置flex和居中属性,简化后代码:
#description h1 span:first-child { font-family: "Croissant One"; font-size: 3.2rem; color: white; }
3. 优化第二个span的样式与动画
保留inline-block属性(或改为flex,效果一致),借助H1的布局实现垂直/水平居中,同时将动画宽度改为自适应内容,避免百分比依赖父容器宽度导致的位置偏移:
#description h1 span:nth-child(2) { font-family: "Croissant One"; font-size: 3.2rem; display: inline-block; overflow: hidden; color: black; background-color: rgb(255, 237, 36); padding: 0 15px; border-right: 0.15em solid white; white-space: nowrap; width: 0; animation: typing 2.5s steps(25) forwards, blink-caret 0.9s step-end infinite; } @keyframes typing { to { width: fit-content; } }
修改后的完整代码
HTML
<section class="container"> <div id="description"> <h1> <span> This element is good, </span> <span> But this one is not centered. </span> </h1> </div> <div id="other-div"> </div> </section>
CSS
.container { margin: auto 30px; background-color: black; border-radius: 1rem; display: flex; } #description { flex: 1; display: flex; justify-content: center; flex-direction: column; color: white; } #description h1 { display: flex; flex-direction: column; align-items: center; gap: 1rem; margin: 0; } #description h1 span:first-child { font-family: "Croissant One"; font-size: 3.2rem; color: white; } #description h1 span:nth-child(2) { font-family: "Croissant One"; font-size: 3.2rem; display: inline-block; overflow: hidden; color: black; background-color: rgb(255, 237, 36); padding: 0 15px; border-right: 0.15em solid white; white-space: nowrap; width: 0; animation: typing 2.5s steps(25) forwards, blink-caret 0.9s step-end infinite; } @keyframes typing { to { width: fit-content; } } @keyframes blink-caret { 50% { border-color: transparent; } } #other-div { flex: 1; display: flex; justify-content: center; }
逻辑说明
- H1作为垂直flex容器,通过
align-items:center让内部span自动水平居中,结合#description的justify-content:center,实现第二个span在整个区域内的垂直居中。 - 动画使用
fit-content自适应文字宽度,避免百分比依赖父容器宽度导致的偏移,确保打字动画始终在居中的黄色块内从左到右展开。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

