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

Svelte中bind:clientHeight无限增长与响应式卡片等高适配问题

等高卡片布局的Svelte实现疑问

布局需求

  • 桌面端采用两列布局,移动端自动切换为单列布局
  • 页面包含4张灰色卡片和1张红色首卡:灰色卡片尺寸由自身内容决定,红色卡片需与相邻卡片保持等高

当前实现情况与问题

使用Svelte的bind:clientWidth和bind:clientHeight属性计算容器尺寸,但必须通过相对定位容器嵌套绝对定位div的方式实现,否则会出现高度无限增长的问题。该方案在桌面端两列布局下表现正常,但在移动端单列布局时,绝对定位导致布局失效;同时当前红色卡片高度偏小,需要将其高度固定为150px。

核心疑问

  1. 如何实现红色卡片高度设置为150px的需求?
  2. 不使用相对/绝对定位的前提下,如何正确获取div的尺寸?

相关代码

<script>
  let containerWidth = 0;
  let containerHeight = 0;

  $: width = containerWidth;
  $: height = containerHeight;
</script>

<div class="col-12 col-md-6 mb-3 border">
  <div
    class="position-relative w-100 h-100 p-3"
    bind:clientWidth={containerWidth}
    bind:clientHeight={containerHeight}
    style="width: {width}px; height: {height}px; background-color: red"
  >
    <div
      class="position-absolute top-0 start-0"
      style="width: {width}px; height: {height}px; background-color: #f7f9fa"
    >
        <div
          class="d-flex justify-content-center align-items-center"
          style="width: {width}px; height: {height}px; background-color: red"
        >
        </div>
    </div>
  </div>
</div>

效果截图

桌面端正常布局效果
移动端布局失效效果


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:55:42