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

Flex布局问题:避免文本容器溢出并实现文本居中

问题:图片旁文本模块适配图片宽度避免溢出

我想实现网页中的一个模块,图片位于左侧或右侧,相邻文本在其所在区域内居中显示。但承载文本的元素默认采用整页宽度,超出可用空间导致文本偏移。尝试过设置不同百分比、min-content等width值均无效,请问如何适配图片可变宽度以避免溢出?

所用HTML和CSS代码片段:

.row {
    display: flex;
    flex:0 0 100%;
    max-height:80%;
    width:100%;
}

.column {
    display: flex;
    flex-direction: column;
    flex:0 0 100%;
    justify-items: center;
    max-height:50%;
    width:100%;
    
}

img {
    display:flex;
    margin: 0;
    padding: 0;
    object-fit: contain;
}
<div class="row" style="max-height: 80%">
    <img src="./images/garden-state.webp">

    <div class="column" style="width:min-content;">
        <div class="title" style="background-color: #1b1b1b; max-height: 30%;"><h3>Garden State</h3></div>
    </div>
</div>

解决方案

核心问题是column类的flex:0 0 100%强制容器占满100%宽度,导致溢出,同时文本居中属性未正确配置。按以下步骤修改:

  • 调整.row布局:添加align-items: center,确保图片与文本容器垂直对齐
  • 修正.column属性:移除flex:0 0 100%,改为flex:1让容器自动填充图片外的剩余空间;同时添加justify-content: center和align-items: center,实现文本在容器内水平+垂直居中
  • 保护图片尺寸:给img设置flex-shrink:0,避免图片被压缩变形

修改后的完整CSS:

.row {
    display: flex;
    align-items: center;
    max-height: 80%;
    width: 100%;
}

.column {
    display: flex;
    flex-direction: column;
    flex: 1;
    justify-content: center;
    align-items: center;
    max-height: 50%;
}

img {
    flex-shrink: 0;
    margin: 0;
    padding: 0;
    object-fit: contain;
}

简化后的HTML(移除冲突的行内width设置):

<div class="row" style="max-height: 80%">
    <img src="./images/garden-state.webp">
    <div class="column">
        <div class="title" style="background-color: #1b1b1b; max-height: 30%;"><h3>Garden State</h3></div>
    </div>
</div>

若要将图片放在右侧,只需调换HTML中img和.column的顺序即可,flex布局会自动调整排列顺序。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:22:41