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

将固定宽高比SVG与动态高度同级元素并排,实现等高布局

解决方案

问题:我有一个固定宽高比的SVG,希望将其放置在一个宽高均动态变化的元素旁,实现二者等高,同时让容器(黄色背景)正确包裹所有子元素。

修改后的代码

CSS 代码

* {
  box-sizing: border-box;
}

.container {
  padding: 10px;
  background-color: yellow;
  font-size: 24px;
  
  display: inline-flex;
}

.pre {
  background-color: blue;
  animation: changePadding 1000ms infinite alternate;
}

.post {
  background-color: red;
  flex-shrink: 0;
}

.post svg {
  height: 100%;
  width: auto;
}

@keyframes changePadding {
  from {padding: 0px 0px;}
  to {padding: 10px 10px;}
}

HTML 代码

<div class="container">
  <div class="pre">Stuff</div>
  <div class="post">
    <svg viewBox="0 0 10 10">
      <circle cx="5" cy="5" r="5" fill="purple"></circle>
      <line x1="0" y1="0" x2="10" y2="10" stroke="red"></line>
    </svg>
  </div>
</div>

关键修改说明

  • 给.post加flex-shrink: 0:防止flex容器压缩SVG的外层容器,确保它能根据SVG实际宽度撑开。
  • SVG设置width: auto:配合height: 100%,让SVG根据自身viewBox的宽高比自动计算宽度,既保证和左侧元素等高,又不破坏原有比例。
  • 保留inline-flex:让容器仅包裹子元素宽度,同时默认的align-items: stretch会自动让两个子元素高度对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:47:03