CSS问题:如何在flexbox中让h1的::before/::after文本居中
解决h1伪元素::before/::after文本居中问题
你的问题出在几个关键CSS设置上:
- 伪元素默认是inline元素,无法直接生效
width/height属性,也没法通过布局属性实现文本居中 font-size未添加单位(如px),导致字体样式不生效- 百分比高度依赖父元素的明确高度,否则无法正确渲染
下面是修改后的完整CSS代码,可解决文本居中问题:
/* ::Before Heading */ .flex-container-heading h1::before{ content: "This is a very cool"; /* General */ background: red; display: flex; justify-content: center; /* 水平居中文本 */ align-items: center; /* 垂直居中文本 */ /* Sizing */ height: 40px; /* 用固定高度替代百分比,避免父元素高度不确定的问题 */ width: 100%; /* Text */ color: white; font-size: 30px; /* 补上px单位 */ font-weight: 900; } /* Heading */ .flex-container-heading h1{ /* General */ display: flex; flex-direction: column; align-items: center; width: 100%; /* 让h1占满容器宽度,确保伪元素的100%width生效 */ margin: 0; /* 清除默认margin,避免不必要的间距 */ /* Text */ color: white; font-size: 40px; /* 补上px单位 */ font-weight: 900; } /* ::After Heading */ .flex-container-heading h1::after{ content: "Isn't it aye?"; /* General */ background: red; display: flex; justify-content: center; align-items: center; /* Sizing */ height: 40px; width: 100%; /* Text */ color: white; font-size: 30px; /* 补上px单位 */ font-weight: 900; }
替代方案(不用flex布局)
如果你习惯用块级元素的方式实现居中,也可以这样设置伪元素:
.flex-container-heading h1::before{ /* ...其他样式 */ display: block; text-align: center; /* 水平居中 */ line-height: 40px; /* 与height值一致,实现垂直居中 */ }
内容的提问来源于stack exchange,提问作者Trevn Jones
相关产品推荐
相关产品推荐

