【问题标题】:Css - Width / Height 100% without dynamic amount of pixelsCss - 宽度/高度 100%,没有动态像素量
【发布时间】:2018-07-15 04:06:46
【问题描述】:

如何将元素的宽度设置为其父元素的 width 减去兄弟元素的未知 width 的 100%。

index.html

<div class="main">
  <div class="sidemenu">
    ...
  </div>
  <div class="contant">
    ...
  </div>
</div>

style.css

.main
{
  width: 100vw;
}

.sidemenu
{
  width: X; /* this value is dymanic, it may change in runtime using JS */
}

.contant
{
  width: ???; /* what do I put here? */
}

如果侧边菜单的宽度是固定的,我可以使用calc(100% - X),但由于宽度是动态的,我如何设置宽度以获取父级的剩余宽度?
我可以仅使用 Css(不使用 JavaScript)来实现这一点吗?

【问题讨论】:

  • 只是想知道,width: auto; 不工作?
  • @Ylama - 不,我希望

标签: css responsive-design width


【解决方案1】:

您可以使用flexbox,因此无需为content 区域指定特定宽度

例如

.main {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

.content { flex: 1; margin-left: 1rem; }

Codepen demo

【讨论】:

  • @GilEpshtain Only display: flex 就足够了,否则它的 flex-direction: column not columns 和 flex-wrap: nowrap 是默认的。
  • @VXp 默认 flex-direction 设置为 row。
  • 我说的是 flex-wrap。
  • @VXp 请重新插入 flex-direction,谢谢。
  • @VXp - 如果回答者回滚您的编辑并要求您停止,请听取他们的意见。不要试图将自己的解释强加于别人的答案。如果您想编写自己的答案,请随时这样做。
【解决方案2】:

我知道这是一篇旧帖子,但这也可以使用 css 变量来完成。

:root {
  --dynamic-width: X;
}
.content {
  width: CALC(100% - var(--dynamic-width));
}

见:https://jsfiddle.net/wzget15m/

【讨论】:

    【解决方案3】:

    您可能要寻找的方法只能使用 js,否则您无法获取元素的宽度以与另一个计算它。

    【讨论】:

    • 这不会解决问题,正如我在问题中提到的 - sizebar 的大小是动态的,因此我不能使用像 12px 这样的固定值
    • OP 不知道从 100% 中减去多少。
    【解决方案4】:

    在主容器中使用display: flex

        .main {
            display: flex;
        } 
        .sidemenu {
            width: X;
        } 
        .contant {
            width: 100%; /* what do I put here? */ 
        }
    

    【讨论】:

    • 这样不行,内容只会溢出屏幕
    • 这发生在宽度:100vw;的 div.main,我删除了这段代码。
    猜你喜欢
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 2015-03-25
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多