Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a flexbox switch to column mode when there isn't enough room for row mode?

Tags:

html

css

flexbox

I have a flexbox like this:

Three boxes side-by-side

When the container is too narrow, it wraps like this:

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

But I want it to do this:

Three boxes stacked vertically

In other words, when the flexbox wraps, I want it to wrap everything at once. It's either completely horizontal or completely vertical.

The flexbox elements aren't all necessarily the same size.

Can it be done?

like image 310
Maxpm Avatar asked Feb 05 '16 21:02

Maxpm


People also ask

How do you get the remaining space in a flex item?

You can use the flex-grow property to force an item to fill the remaining space on the main axis of a flex container. The item will expand as much as possible and occupy the free area.

How do you make a flexbox column?

Approach: To create a two-column layout, first we create a <div> element with property display: flex, it makes that a div flexbox and then add flex-direction: row, to make the layout column-wise. Then add the required div inside the above div with require width and they all will come as columns.

How do I add more space to my flexbox?

To set space between the flexbox you can use the flexbox property justify-content you can also visit all the property in that link. We can use the justify-content property of a flex container to set space between the flexbox.


1 Answers

Simplest way is to use a media query (or a script is needed).

Set a min-width to your parent element (or check before hand) and a matching media query, which change flex-direction to column

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

Side note

If you do want to dig into scripting for this, an eventlistener on resize and load, checking for a scrollbar like this, and you have another way to change your style.

So by not setting wrap to your row, it will at some point create a scrollbar, either if page is to narrow on load or if user resize.

//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
}

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

like image 138
Asons Avatar answered Sep 28 '22 08:09

Asons