HTML & CSS:flex布局下图片间的圆点无法垂直居中如何解决?
圆点与图片垂直居中实现方案
核心修改点
- 给flex容器
.features添加align-items: center属性,控制所有子元素在垂直方向居中对齐 - 若需要圆点精准和图片区域(排除下方figcaption文字)对齐,可给
.dot添加transform: translateY(-20px),数值可根据figcaption实际高度微调
完整修改后CSS代码
.features { padding: 20px; display: flex; flex-direction: row; color: rgb(0, 0, 0); align-items: center; /* 新增垂直居中属性 */ } .features figure { margin: auto; width: 200px; border: 1px solid rgb(117, 117, 117); border-radius: 10px; box-shadow: rgb(0, 0, 0) 0px 0px 5px; text-align: center; } .figImg{ object-fit: contain; width: 200px; border-radius: 10px 10px 0 0; } header .logo a { background: url("My Post.png"); display: inline-block; width: 350px; height: 250px; text-indent: -99999999px; background-repeat: no-repeat; background-size: 350px; position: relative; top: -160px; color: white; } .bod { padding-left: 25px; padding-right: 25px; font-family: 'Lato', 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans'; } p { background: rgb(238, 238, 238); border-radius: 10px; border: 2px solid black; padding: 10px; box-shadow: rgb(0, 0, 0) 0px 0px 5px; } .dot { height: 12px; width: 12px; background-color: rgb(238, 238, 238); border-radius: 50%; display: inline-block; border: 2px solid black; /* 可选:如果需要和图片区域对齐,取消下行注释并调整数值 */ /* transform: translateY(-20px); */ }
原理解释
Flex布局中,flex-direction: row时主轴为水平方向,交叉轴为垂直方向,align-items属性专门用来控制子元素在交叉轴的对齐规则,默认值为stretch会把子元素高度拉满容器,改成center后所有子元素就会自动沿垂直方向居中对齐。
另外你原有代码里.features figure规则重复定义了两次,宽度属性后面的200px会覆盖前面的100px,建议删掉重复的规则避免后续维护出错。
内容的提问来源于stack exchange,提问作者Novakron
相关产品推荐
相关产品推荐

