Home > Mobile >  How to stop flex-box from pushing other elements out of the container?
How to stop flex-box from pushing other elements out of the container?

Time:02-20

It's a bit hard to explain, but consider a flex header with a menu and then something else on the right which is fixed width. As the window size shrinks in width, there is less room for the menu. Eventually, the menu pushes the other thing out of the container.

enter image description here

Note how the "other thing" falls out to the right.

Adding overflow: hidden to the menu container element makes it so the "other thing" doesn't get pushed. However, this also prevents the drop-down menu from showing, of course. I tried to work around it by setting overflow-x: hidden; overflow-y: visible but this is apparently not a valid setting.

Better, but no drop-down menu

enter image description here

(Ignore that "Item 1" has been hidden. In the real code "Item 5" would have been moved to an overflow menu -- not included in the demo here.)

Question

How can I make it work like the bottom example, but without adding overflow: hidden to the menu? That is, how can I stop flex-box from pushing the "other thing" out to the right?

CodePudding user response:

TL;DR. See the CodePen example linked at the bottom.

Limited spaces multiple elements = unavoidably overflowing content

Your .logo takes up 50px and the .other-thing takes up 200px. Because you didn't set flex-wrap to the .menu, its width won't go smaller than the content. That means, as the viewport width shrinks, your .header will inevitably overflow.

Setting your .menu with overflow: hidden; wouldn't work in your favor either. Once your Item 1 and Item 5 are cropped out, your users won't be able to scroll to them because overflow: hidden; prohibits it.

flex-wrap: wrap; and @media for better responsiveness

Adding flex-wrap to the .menu would be a good start. That way, in small viewports, the .menu will flexibly wrap as needed. Also, to accommodate a wrapping behavior, I'd suggested you remove explicit height from .header and use padding for consistency.

Using @media for responsive layout will be a better long-term solution for you. Here I suggested resizing the .logo and .other-thing on smaller viewport as an example. In real life, you'd probably want to introduce a mobile-only menu UI (e.g. hamburger button) rather than keeping all menu items visible. Say, in a smaller screen (< 640px), showing 50px logo and 200px other thing with all those individual menu items simply won't work elegantly.

See this CodePen example here

CodePudding user response:

Use example 2 and remove the overflow-hidden class. Set dropdown-menu to display: none;. I added a class called item-4 to your first child of menu. Then you can use the following CSS to show dropdown-menu.

.dropdown-menu {
  display: none;
}

.dropdown > div.item-4:hover ~ .dropdown-menu {
  display: block;
}

Fiddle

  • Related