You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Flexbox实现图片与链接水平同行居中且垂直对齐?

解决图片与链接同行居中且垂直对齐问题

当前代码中,.box设置了flex-direction: column,导致内部图片和链接垂直排列,再加上图片未做水平居中处理,才出现了图片居左、链接换行的问题。按以下方式修改CSS即可解决:

修改要点

  • 将.box的flex-direction: column改为row,让图片和链接横向排列
  • 给.box添加align-items: center实现垂直居中,justify-content: center实现整体水平居中
  • 移除图片上无效的justify-content和text-align属性(这两个是flex容器专属属性,作用在图片元素上不生效)
  • 可选:给.box添加gap属性,灵活控制图片和链接之间的间距

修改后的完整CSS代码

html,
body {
    height: 100%;
    margin: 0; /* 移除默认边距,避免页面出现滚动条 */
}
.container {
    height: 100%;
    min-height: 100%;
    display: flex;
    flex-direction: column;

    .box {
        text-align: center;
        color: black;       
        display: flex;
        flex-direction: row; /* 改为横向排列 */
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
        gap: 10px; /* 可选:设置图片与链接的间距 */
    }
    .box img {
        width: 100px;
        height: 100px;
    }           
    .item1 {
        background-color: white;
        height: 25%;
    }   
    .item2 {
        background-color: silver;
        height: 25%;
    }
    .item3 {
        background-color: white;
        height: 25%;
    }
    .item4 {
        background-color: silver;
        height: 25%;
    }
    .item5 {
        background-color: white;
        height: 25%;
    }
}

HTML代码无需修改,保持原结构即可。

内容的提问来源于stack exchange,提问作者k4mk4m

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:05:33