Jimmy Coldfeet
Jimmy Coldfeet

Reputation: 73

How to change the width of a CSS flex-box column?

I have a menu div that fills 100% of its container height, and beside it, to the right, are the header, body and footer sections.

I managed to do this with the CSS flex property. However, I want to change the amount of width the "menu" div takes out of the container, as in, making it 10% width of container's width, and make the rest divs fill what's left (even if the "menu" div is hidden at a later time).

JS Fiddle of what I have right now: https://jsfiddle.net/jf29vr0x/3/

.container {
  display: flex;
  flex-flow: column wrap;
  width: 75%;
  height: 500px;
  position: relative;
  margin: 0 auto;
}

.menu {
  flex: 0 0 100%;
  background: lightblue;
}

.header {
  flex: 0 0 10%;
  background: lightgray;
}

.body {
  flex: 0 0 80%;
  background: purple;
}

.footer {
  flex: 0 0 10%;
  background: lightgreen;
}
<div class="container">

  <div class="menu">
    Menu
  </div>

  <div class="header">
    Header
  </div>

  <div class="body">
    Body
  </div>

  <div class="footer">
    Footer
  </div>

</div>

I found that if I set the width explicitly on the "menu" class, it resizes it, but the rest of the boxes don't fill the space left, unless I also explicitly state their width to 100%. However, doing this, makes the container overflow, and because the container is aligned to the center, it looks off.

I could also set the width to 90% (on header, footer body) and 10% on the menu, but the menu is sometimes set to display: none;, so when it disappears, the other layout parts are only going to be 90% of container's width.

Is there any way of doing this with only flex-box properties? I don't understand very well what flex-shrink and flex-grow are about, but I think they only affect (in this case) the height?

Thank you.

Upvotes: 7

Views: 25374

Answers (1)

ratherblue
ratherblue

Reputation: 2108

You have to add a wrapper around the right column, and then only specify flex-basis on the .menu element.

.container {
  display: flex;
  width: 75%;
  height: 500px;
  position: relative;
  margin: 0 auto;
  height: 500px;
  overflow: hidden;
}

.right-col {
  flex-flow: column wrap;
  flex-grow: 1;
  height: 100%;
  display: flex;
}

.menu {
  flex-basis: 10%;
  background: lightblue;
}

.header {
  flex: 0 0 10%;
  background: lightgray;
}

.body {
  flex: 0 0 80%;
  background: purple;
}

.footer {
  flex: 0 0 10%;
  background: lightgreen;
}
<div class="container">
  <div class="menu">Menu</div>
  <div class="right-col">
    <div class="header">Header</div>
    <div class="body">Body</div>
    <div class="footer">Footer</div>
  </div>
</div>

Fiddle: https://jsfiddle.net/jf29vr0x/11/

Now when the menu is hidden, the right column expands the full amount.

Upvotes: 9

Related Questions