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

如何同时实现max-width、max-height、保持图片宽高比并避免CLS问题

可行实现方案

以下方案可在所有现代浏览器中同时满足三个要求,无CLS、宽高比正确、且严格遵守max-width:90px、max-height:45px的限制:


完整代码

<div class="container">
  <div class="logo">
    <img width="115" height="100" alt="">
  </div>
  
  <div class="name">
    Company name
  </div>
</div>
.container {
    display: flex;
    align-items: center;
}

.logo {
  /* 提前预占最大允许的展示空间,从根源避免CLS */
  width: 90px;
  height: 45px;
  flex-shrink: 0;
  /* 可选:图片尺寸小于容器时居中展示 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo img {
    max-width: 100%;
    max-height: 100%;
    height: auto;
    width: auto;
    /* 保证图片缩放时保持原始宽高比,无变形 */
    object-fit: contain;
}

.name {
  margin-left: 15px;
}
setTimeout(function() {
document.querySelector('img').src = 'https://via.placeholder.com/115x100';
}, 500);

方案说明

  • 无CLS:.logo容器在页面渲染初始阶段就固定占用90px×45px的空间,图片动态加载不会改变容器尺寸,周围元素布局不会发生偏移
  • 严格遵守尺寸限制:图片最大只能撑满父容器,自然满足max-width:90px、max-height:45px的要求
  • 宽高比正确:图片保留width: auto、height: auto属性,配合object-fit: contain,缩放时完全保留原始宽高比,不会出现拉伸变形

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:54:05