bvcx bvcx - 3 months ago 31
CSS Question

Flexbox sidebar with max-width

Is it possible to set max-width on the sidebar in my flexbox layout without affecting the content area (article)? Changing the max-width now also affects the content area. I want the current functionality, with the layout being responsive, but also setting a max-width on the sidebar.

Codepen

HTML:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="flex-container">

<nav class="nav">
<ul>
<li><a href="#">Menu1</a></li>
<li><a href="#">Menu2</a></li>
<li><a href="#">Menu3</a></li>
</ul>
</nav>

<article class="article">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor ....</p>
</article>

</div>

</body>
</html>


CSS:

.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
text-align: center;
}

.flex-container > * {
padding: 15px;
-webkit-flex: 1 100%;
flex: 1 100%;
}

.article {
text-align: left;
}

.nav {
background:#eee;
}

.nav ul {
list-style-type: none;
padding: 0;
}

.nav ul a {
text-decoration: none;
}

@media all and (min-width: 768px) {
.nav {
text-align:left;
-webkit-flex: 1 auto;
flex:1 auto;
-webkit-order:1;
order:1;
}

.article {
-webkit-flex:5 0px;
flex:5 0px;
-webkit-order:2;
order:2;
}
}

Answer

Right now you're telling both your <nav> and your <article> to grow as much as they can with this declaration:

.flex-container > * {
    flex: 1 100%;
}

You should define the default size of your <nav> element before the remaining space is distributed with auto instead of 100%. The auto keyword means "look at my width or height property".

.flex-container > .nav {
    flex: 1 1 auto;
    max-width: 300px;
}

Right there you're telling your <nav> to grow and shrink and never be wider than 300px (it's gonna be actually 330px because the padding isn't considered when doing this calculations)

Edit:

So in order to solve your problem I had to rewrite some code, here's a working fiddle

Comments