Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Flexbox layout losing proportions when reduced in size
Flexbox items can lose their intended proportions when the container shrinks, causing layout distortion. This happens due to default flex shrinking behavior and minimum size calculations.
The Problem
By default, flex items have flex-shrink: 1 and min-width: auto, which can cause unexpected shrinking behavior when the container becomes smaller than the content.
<div class="flex-container">
<div class="flex-item">Item 1 with long content</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
<style>
.flex-container {
display: flex;
width: 300px;
border: 1px solid #ccc;
}
.flex-item {
flex: 1;
padding: 10px;
background: lightblue;
margin: 2px;
}
</style>
Solution: Control Flex Shrinking
To maintain proportions when the container shrinks, control the flex shrinking behavior:
<style>
* {
flex-shrink: 0;
min-width: 0;
min-height: 0;
}
.flex-container {
display: flex;
width: 200px; /* Smaller container */
border: 1px solid #ccc;
overflow: hidden;
}
.flex-item {
flex: 1 0 auto; /* grow shrink basis */
padding: 10px;
background: lightblue;
margin: 2px;
}
</style>
CSS Properties Explained
| Property | Value | Effect |
|---|---|---|
flex-shrink |
0 | Prevents flex items from shrinking |
min-width |
0 | Allows items to shrink below content width |
min-height |
0 | Allows items to shrink below content height |
Alternative Approach
Instead of global rules, apply specific flex values to maintain better control:
.flex-item {
flex: 1 1 0%; /* Equal flex basis */
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Conclusion
Use flex-shrink: 0 and min-width: 0 to prevent unwanted shrinking in flexbox layouts. Consider using overflow: hidden for content that exceeds available space.
Advertisements
