Reputation: 3155
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:
CodePen: http://codepen.io/anon/pen/RPNpaP.
Any idea what I'm doing wrong?
Upvotes: 301
Views: 446162
Reputation: 78756
I'd recommend to use flex/flex-basis
properties rather than width/height
.
.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 below shows how to set the first column to 50px
fixed width.
.flexbox {
display: flex;
}
.flexbox > div {
outline: 1px solid;
}
.red {
flex: 0 0 50px;
color: red;
}
.green {
flex: 1;
color: green;
}
.blue {
flex: 1;
color: blue;
}
<div class="flexbox">
<div class="red">1</div>
<div class="green">2</div>
<div class="blue">3</div>
</div>
More info
Let's say flex-direction is set to row (default value):
flex-basis overrides width if specifically declared anything other than flex-basis: auto (default value).
with flex-basis: auto (or not specified), it first checks for width, if none, it uses the elements content width.
flex-basis still obeys max-width & min-width.
The sizing follows this formula:
content —> width —> flex-basis (limited by max-width & min-width)
Same thing for flex-direction: column, height, max-height, and min-height.
I think it is best to practice using flex-basis over width/height, this way the results are always consistent.
Upvotes: 678
Reputation: 1413
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;
}
Upvotes: 10
Reputation: 2146
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%;
}
Upvotes: 17