【问题标题】:Set a div that has a percentage (%) width to have a min-width of its largest content将具有百分比 (%) 宽度的 div 设置为其最大内容的最小宽度
【发布时间】:2019-01-11 07:24:30
【问题描述】:

我正在尝试构建一个随页面宽度增长的侧边菜单,但是当缩小时不会折叠到菜单的任何内容中。

现在我可以使用min-width: 和一些静态像素数来防止菜单折叠,但是由于菜单的内容可以变化,我希望菜单始终具有最大元素的最小宽度。

这可以使用 javascript 来实现,但是有没有优雅的 CSS 解决方案呢?

这里是一个带有示例的笔,你可以滑动编辑器窗口折叠菜单:

CodePen

基本元素结构:

html, body {
  height: 100%;
}

.container {
  position: fixed;
  top:0;
  left:0;
  width: 30%;
  height:100%;
  background: rgba(255,0,0,0.4);
}
<div class="container">
  <ul>
    <li>Variable</li>
    <li>Width</li>
    <li>Content</li>
    <li>Do not collapse long text</li>
  </ul>
</div>

感谢大家的帮助

【问题讨论】:

    标签: css width min percentage


    【解决方案1】:

    还有弹性盒

    html,
    body {
      height: 100%;
    }
    
    .container {
      position: fixed;
      top: 0;
      left: 0;
      min-width:30vw;
      display: flex;
      height: 100%;
      background: rgba(255, 0, 0, 0.4);
    }
    <div class="container">
      <ul>
        <li>Variable</li>
        <li>Width</li>
        <li>Content</li>
        <li>Do not collapse long text</li>
      </ul>
    </div>

    【讨论】:

      【解决方案2】:

      您可以使用 CSS 网格来模拟这种行为

      html, body {
        height: 100%;
        margin:0;
      }
      
      .container {
        position: fixed;
        display:grid;
        top:0;
        left:0;
        grid-template-columns:minmax(max-content,30vw);
        height:100%;
        background: rgba(255,0,0,0.4);
      }
      <div class="container">
        <ul>
          <li>Variable</li>
          <li>Width</li>
          <li>Content</li>
          <li>Do not collapse long text</li>
        </ul>
      </div>

      【讨论】:

      • 谢谢,这也适用于max-width,我忘了在我的问题中包含它
      猜你喜欢
      • 2011-03-02
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2013-03-13
      • 2021-02-25
      相关资源
      最近更新 更多