【问题标题】:How to hide an element if it does not fit in a flex layout?如果元素不适合弹性布局,如何隐藏它?
【发布时间】:2019-01-02 17:23:33
【问题描述】:

我正在尝试制作一个包含 3 个项目的水平 flexbox div。每个都有一个最小宽度,我想隐藏它们,因为屏幕太小而无法容纳它们。如果我知道所有 3 个 div 的宽度,我会使用媒体查询将 div 隐藏在正确的断点处。问题是 div1 是具有动态宽度的图像(在示例中以随机宽度重新创建)

如果元素不适合 flexbox 容器,有什么方法可以隐藏它?

这有点难以解释,但希望运行这段代码 sn-p 几次将显示我所追求的:

let width = (Math.random()*600)
document.getElementById('one').style.minWidth = width + 'px'
.root {
  display: flex;
  justify-content: space-between;
}

.one {
  background-color: red;
}

.two {
  min-width: 200px;
  background-color: green;
}

.three {
  min-width: 300px;
  background-color: yellow;
  flex: 1
}
<div class="root">
  <div id="one" class="one">
    unknown width
  </div>
  <div class="two">
    hide me if im off the screen
  </div>
  <div class="three">
    hide me if im off the screen
  </div>
</div>

【问题讨论】:

  • 这就是我正在做的事情,示例中的 div1 是 img,问题是宽度会根据照片尺寸(基本上是随机的)而变化,所以我基本上是在尝试在剩余空间
  • 如果你使用flex-wrap: wrap,你能避免隐藏它们吗?
  • flex-wrap 非常接近!但我需要隐藏它们而不是溢出
  • @dippas 图像需​​要以固定的高度和自动宽度完全显示,另外两个只有在有足够空间的情况下才能显示

标签: javascript html css flexbox


【解决方案1】:

由于您有固定高度的图像,您可以将root 设置为最大高度并使用flex-wrap: wrap

let width = (Math.random()*600)
document.getElementById('one').style.minWidth = width + 'px'
.root {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  overflow:hidden;
  max-height:50px;
  overflow-y:hidden;
}

.one {
  background-color: red;
  height: 50px;
}

.two {
  min-width: 200px;
  background-color: green;
}

.three {
  min-width: 300px;
  background-color: yellow;
  flex: 1
}
<div class="root">
  <div id="one" class="one">
    unknown width
  </div>
  <div class="two">
    hide me if im off the screen
  </div>
  <div class="three">
    hide me if im off the screen
  </div>
</div>

http://jsfiddle.net/4y39h8jn/1/

【讨论】:

  • 如何在最后一个元素之后添加一个元素?假设将显示 4/10,我想添加一个形状相同的元素,带有三个点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2016-04-16
相关资源
最近更新 更多