Flexbox - Advanced
With Flexbox, you can create responsive designs and fluid layouts that work seamlessly from smartphones to desktops.
Responsive Design and Flexbox
Responsive web design allows a website to adapt its layout and presentation to fit various screen sizes, optimizing the website across different devices.
For instance, when the browser window is wide, multiple items can be laid out in a row horizontally, but as the window narrows, the items can be stacked vertically to provide a better user experience.
/* By default, arrange items in the container horizontally */ .flex-container { display: flex; flex-direction: row; } /* If the screen width is 600px or less, arrange items vertically in the container */ @media (max-width: 600px) { .flex-container { flex-direction: column; } }
Dynamic Flexbox Item Alignment
The main properties used when aligning Flexbox items are flex-grow
, flex-shrink
, and flex-basis
.
flex-grow
Determines how a flex item will grow to occupy free space within the flex container.
A value of 0
means the item will not grow to fill available space, while a value of 1
or more allows the item to grow and occupy remaining space in relation to others.
flex-shrink
Determines how a flex item will shrink when there's insufficient space in the flex container.
A value of 0
means the item will not shrink, whereas a value of 1
or more allows the item to shrink relative to others when space is limited.
flex-basis
Specifies the initial size of a flex item.
For example, flex-basis: 200px;
means the initial size of each item is 200px.
A value of auto
allows the item to follow its natural size as determined by the content.
.item { flex-grow: 1; /* Distribute remaining space evenly among items */ flex-shrink: 1; /* Shrink items proportionally to each other */ flex-basis: 200px; /* Initial size of item is 200px */ }
flex
Property
The flex
property lets you set flex-grow
, flex-shrink
, and flex-basis
in one go.
Each property's values apply in order when using this shorthand.
/* flex: <flex-grow> <flex-shrink> <flex-basis> */ .item { flex: 1 1 0; }
In this code:
- The
flex-grow
value is 1, meaning the items will distribute remaining space equally. - The
flex-shrink
value is also 1, so items will shrink evenly as the space reduces. - The
flex-basis
value is 0, making the initial size of the items depend on their content size.
Using the flex
property simplifies your code by allowing you to set multiple attributes at once.
Note that flex: 1;
is equivalent to setting flex-grow: 1;
, flex-shrink: 1;
, and flex-basis: 0%;
.
This means that items will grow to fill additional space, shrink when necessary, and have an initial size set to 0%.
Try entering the code with the emphasized parts highlighted by asterisks.
What is the property for setting the direction of flex in Flexbox?
flex-direction
flex-grow
flex
flex-basis
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help