html - 当没有足够的空间用于行模式时,如何使 flexbox 切换到列模式?

标签 html css flexbox

我有一个像这样的 flexbox:

Three boxes side-by-side

当容器太窄时,它会像这样包裹:

Two boxes on the first row, and one box on the second row

但我希望它这样做:

Three boxes stacked vertically

换句话说,当 flexbox 换行时,我希望它一次换行所有内容。要么完全水平,要么完全垂直。

flexbox 元素不一定都是相同的大小。

可以吗?

最佳答案

最简单的方法是使用媒体查询(或者需要脚本)。

为您的父元素设置一个min-width(或事先检查)和一个匹配的媒体查询,这会将flex-direction更改为column

@media screen and (max-width: 500px) {
  .classname {
    flex-direction: column;
  }
}

边注

如果您确实想为此深入研究脚本,一个调整大小和加载的事件监听器,检查这样的滚动条,您还有另一种方法来改变您的风格。

因此,如果不为您的行设置换行,它会在某个时候创建​​一个滚动条,无论是在页面加载时变窄还是用户调整大小。

//Horizontal Scrollbar
(function($) {
    $.fn.hasHorizontalScrollBar = function() {
        return this.get(0) ? this.get(0).scrollWidth > this.innerWidth() : false;
    }
})(jQuery);

//Vertical Scrollbar
(function($) {
    $.fn.hasVerticalScrollBar = function() {
        return this.get(0) ? this.get(0).scrollHeight > this.innerheight() : false;
    }
})(jQuery);


//use it like this
if($("#element").hasVerticalScrollbar()){
    //do whatever you'd like to
}

来源:https://hasin.me/2013/08/17/detecting-if-a-dom-element-has-scrollbar/

关于html - 当没有足够的空间用于行模式时,如何使 flexbox 切换到列模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35233818/

相关文章:

javascript - 使用 jQuery UI "Accordion and Droppable"

html - 从sqlite数据库获取时不解释换行符?

javascript - 使用 css 遇到一些字符后转到新行

javascript - 将所有文本链接转换为实际链接

javascript - Vue.js - 在点击事件上添加类

html - Display flex 覆盖显示网格布局

html - 尝试用 Angular 更新可编辑 div 中的文本内容的变量时,可编辑 div 的奇怪行为。有什么解释吗?

javascript - 使用 jQuery 选择子元素

html - 使用 flexbox 跨列打破无序列表元素

twitter-bootstrap - 可扩展的布局过渡