求助:如何使页面中的3个figure元素在同一行显示?
解决figure元素无法同行显示的问题
先梳理下原代码里的核心问题,再给你对应的修复方案:
1. 先修复HTML标签嵌套错误
原代码里h2和figure的标签交叉嵌套,浏览器解析时会自动补全错误标签,直接打乱布局逻辑。正确的结构应该是figure包含h2和figcaption,修正后的核心HTML部分如下:
<center> <div class="about" id="abt"> <div class="abtcontent"> <h1 style="color: black; margin-bottom: 0; border-bottom: 5px solid black; border-radius: 5px; width: 7%; margin-left: 0;"><b>About</b></h1> <p style="color:black">Lorem Ipasum</p> <center> <!-- 修正类名:把hero.sec改成hero-sec,避免类名里的点导致选择器失效 --> <div class="hero-sec"> <figure> <h2><span class="num" data-val="650">000</span></h2> <figcaption>Lines of Code</figcaption> </figure> <figure> <h2><span class="num" data-val="50">000</span></h2> <figcaption>Scam Servers detected</figcaption> </figure> <figure> <h2><span class="num" data-val="10"></span></h2> <figcaption>Legit Servers listed</figcaption> </figure> </div> </center> </div> </div> </center>
2. 用CSS实现同行布局
方案一:Flex布局(推荐,灵活度高)
给父容器.hero-sec设置flex属性,轻松实现同行排列,还能控制间距和对齐方式:
.hero-sec { display: flex; gap: 2rem; /* 三个figure之间的间距,可按需调整 */ justify-content: center; /* 整体水平居中 */ align-items: center; /* 内容垂直居中 */ } /* 可选:让每个figure内部文字居中,避免排版混乱 */ .hero-sec figure { text-align: center; /* 如果需要三个元素平分宽度,可添加flex: 1; */ }
方案二:inline-block布局
如果不想用flex,也可以给每个figure设置行内块属性:
.hero-sec { text-align: center; /* 让inline-block元素水平居中 */ } .hero-sec figure { display: inline-block; margin: 0 1rem; /* 控制元素间间距 */ text-align: center; }
原代码无效的原因
- 类名错误:原HTML里
class="hero.sec"是错误写法,CSS里的.hero.sec是选择同时拥有hero和sec两个类的元素,而非类名为hero.sec的元素,导致CSS规则完全没生效。 - 标签嵌套错误:交叉嵌套的标签会让浏览器解析出异常DOM结构,直接影响布局。
figure默认是块级元素:即使父容器设了display: inline,块级元素依然会独占一行,必须修改其显示属性或用flex等布局方式。
内容的提问来源于stack exchange,提问作者upper-productions
相关产品推荐
相关产品推荐

