Is there a way to make <div>
be responsive and take the continuous range of values between its min-width and max-width as the screen size is changed?
A sample of my current HTML structure is below and in this JSFiddle playground. The end goal is to make the width of the <div>
with the blue background slowly decrease from its max-width to its min-width as the screen size is reduced.
HTML
<div class="bar-container">
<div class="left-bar">
<div class="grey"></div>
</div>
<div class="right-bar">
<div class="wrapper">
<div class="red"></div>
<div class="blue"></div>
</div>
<div class="yellow"></div>
</div>
</div>
CSS
.bar-container {
background-color: black;
height: 50px;
display: flex;
justify-content: space-between;
}
.left-bar {
display: flex;
}
.right-bar {
display: flex;
}
.grey {
width: 100px;
background-color: grey;
}
.wrapper {
display: flex;
}
.red {
width: 100px;
background-color: red;
}
.blue {
min-width: 100px;
max-width: 200px;
width: 100%;
background-color: blue;
}
.yellow {
width: 100px;
background-color: yellow;
}
3
Answers
After several hours spent on this, I have managed to find a solution. I was focusing too much on the
blue
<div>
itself, I did not pay attention to the overall HTML structure. To obtain the desired behaviour,theright-bar
<div>
could be made to occupy the whole space until it reaches theleft-bar
<div>
by setting itswidth
to100%
. The children elements can be aligned to the right. Same for thewrapper
<div>
. Theblue
<div>
is assigned awidth
of100%
,min-width
of100px
and max-width of200px
.The final CSS is something like below and the HTML is unchanged.
Yes, there is a way to do it in CSS.
by using
min-width:800px;
ormax-width:800px;
or you can do it by using Bootstrap Columns, It is a better way to make the best possible responsive divisions of the pageYou want the blue div to fill up the entire screen for displays smaller than 768px and gradually go narrower as the screen size is shrunk. You can accomplish this by setting the width property’s transition effect to 1 and utilizing the flex-grow: 1 style.
Then add wrapper div to occupy all available space and the blue div to have a set width of 200px for screens 768px and larger. For the blue div, we set flex-grow: 0 and width: 200px, and for the wrapper div, we set flex-grow: 1 and add a padding-right transition effect.
In order for the wrapper div to occupy all available space, we additionally add a:after pseudo-element to the wrapper div with a huge flex-grow value and a padding-right value equal to the width of the yellow div. We also make the right bar div shrinkable. This frees up space so that the yellow div may be seen.
In order to prevent the yellow div from changing size, we add it last and give it a constant width of 100px. We also set its flex-grow and flex-shrink values to 0.