使用Flexbox实现容器内图片下方文字居中的问题
Flexbox实现图片与下方文字居中对齐问题解决
我想用Flexbox实现图片和下方文字的居中对齐,现在文字已经正确居中,但对应的图片看起来略微偏左,和文字不对齐。
现有CSS代码
body { font-family:'Times New Roman', Times, serif; display: flex; flex-direction: column; align-items: center; justify-content: center; } .infoheader { font-size: 36px; font-weight: 300; margin-bottom: 12px; text-align: center; } .body { display: flex; gap: 10px; text-align: center; justify-content: center; } .card { max-width: 200px; } .fishes { height: 100px; width: 100px; }
现有HTML代码
<body> <div class="infoheader">An Example Assortment of Fishes:</div> <div class="body"> <div class="card"> <img class="fishes" src="./fishes/onefish.jpg" alt="funny fish"> <div class="text">what would happen if i added a very very very long line of text</div> </div> <div class="card"> <img class="fishes" src="./fishes/bluefish.jpg" alt="funny fish"> <div class="text">This is some subtext under an image.</div> </div> <div class="card"> <img class="fishes" src="./fishes/fish.jpg" alt="SEAL"> <div class="text">This is some subtext under an image.</div> </div> <div class="card"> <img class="fishes" src="./fishes/twofish.jpg" alt="funny fish"> <div class="text">This is some subtext under an image.</div> </div> </div> </body>
我原本以为给.body加justify-content: center;和text-align: center就能让图片文字都居中,但只有文字对齐了,图片偏左。
修复方案
有两种简单的方法可以解决这个问题:
方法一:将.card设置为Flex容器
修改.card的CSS样式,让它成为垂直排列的Flex容器并居中内部元素:
.card { max-width: 200px; display: flex; flex-direction: column; align-items: center; }
这样.card内的图片和文字都会在容器内水平居中,实现完美对齐。
方法二:给图片设置自动水平外边距
直接给.fishes类添加margin: 0 auto;,让图片在.card的宽度范围内自动居中:
.fishes { height: 100px; width: 100px; margin: 0 auto; }
问题原因
之前的问题核心在于:.card的max-width是200px,而图片仅100px宽,默认状态下图片会左对齐显示;而文字因为.body设置了text-align: center,会在200px的.card容器内居中。两者对齐方式不一致,就导致了图片看起来比文字偏左的视觉效果。上面两种方法都是让图片也在.card容器内水平居中,从而和文字对齐。
内容的提问来源于stack exchange,提问作者olive
相关产品推荐
相关产品推荐

