将宽度为百分比(%)的div设置为其最大内容的最小宽度

时间:2018-08-03 11:49:32

标签: css width min percentage

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

现在,我可以使用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>

感谢所有帮助

2 个答案:

答案 0 :(得分:2)

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

    @Value("${apple.native}")
    private String Native;

    @Value("${apple.cost}")
    private Double cost;

    @Value("${apple.name}")
    private String name;
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);
}

答案 1 :(得分:1)

也是flexbox

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>