How to set a fixed width column with CSS flexbox
HtmlCssFlexboxHtml Problem Overview
CodePen: http://codepen.io/anon/pen/RPNpaP.
I want the red box to be only 25 em wide when it's in the side-by-side view - I'm trying to achieve this by setting the CSS inside this media query:
@media all and (min-width: 811px) {...}
to:
.flexbox .red {
width: 25em;
}
But when I do that, this happens:
http://i.imgur.com/niFBrwt.png
Any idea what I'm doing wrong?
Html Solutions
Solution 1 - Html
You should use the flex
or flex-basis
property rather than width
. Read more on MDN.
.flexbox .red {
flex: 0 0 25em;
}
The flex
CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:
flex-grow: 0; /* do not grow - initial value: 0 */
flex-shrink: 0; /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height - initial value: auto */
A simple demo shows how to set the first column to 50px
fixed width.
.flexbox {
display: flex;
}
.red {
background: red;
flex: 0 0 50px;
}
.green {
background: green;
flex: 1;
}
.blue {
background: blue;
flex: 1;
}
<div class="flexbox">
<div class="red">1</div>
<div class="green">2</div>
<div class="blue">3</div>
</div>
See the updated codepen based on your code.
Solution 2 - Html
In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.
flex-basis: 25%;
This will be a lot smoother when testing.
// VARIABLES
$screen-xs: 480px;
$screen-sm: 768px;
$screen-md: 992px;
$screen-lg: 1200px;
$screen-xl: 1400px;
$screen-xxl: 1600px;
// QUERIES
@media screen (max-width: $screen-lg) {
flex-basis: 25%;
}
@media screen (max-width: $screen-md) {
flex-basis: 33.33%;
}
Solution 3 - Html
Actually, if you really want to use the width CSS property another workaround for this is to apply this:
.flexbox .red {
width: 100%;
max-width: 25em;
}