Home > Enterprise >  How to stop one columns width from shrinking and have the other column fill the remaining width
How to stop one columns width from shrinking and have the other column fill the remaining width

Time:12-15

    <div class='container'>
      <div class='col-1'></div>
      <div class='col-2'></div>
    </div>
.container{
  width: 100vw;
  height: 100vh;
  display: flex;
}

.col-1{
  width: 40%;
  height: 100%;
  background-color: blue;
}

.col-2{
  width: 60%;
  height: 100%;
  background-color: red;
}

How can I achieve the result of col-1 adjusting its width up until a certain point? (let's say its width will stop shrinking at 20 rem, and col-2's width will auto adjust to fill the remaining width of the container space available?

CodePudding user response:

Start ditching flex in favor of grid, it's so much easier and more powerful as well:

body { margin: 0; }

.container {
  width: 100vw;
  height: 100vh;
  display: grid;
  grid-template-columns: minmax(15rem, 1fr) 1fr;
}

.col-1 {
  background-color: blue;
}

.col-2 {
  background-color: red;
}
<div class='container'>
  <div class='col-1'></div>
  <div class='col-2'></div>
</div>

CodePudding user response:

i think this should work!

.container{
  width: 100vw;
  height: 100vh;
  display: flex;
}

.col-1{
  width: 20%;
  height: 100%;
  background-color: blue;
}

.col-2{
  width: calc(100% - 100px);
  height: 100%;
  background-color: red;
}
  <div class='container'>
      <div class='col-1'></div>
      <div class='col-2'></div>
    </div>

by replacing width: 60% from .col-2 to width: calc(100% - 100px); using calc!

CodePudding user response:

you can use display: grid; instead of flex. then set grid-template-columns: 20rem 1fr; and then set both col-1 and col-2 width to 100%. that if you change the grid-template-columns both col-1 and col-2 will adjust with it!

CodePudding user response:

If you're using display: flex you should use the flex methods of defining the scaling (instead of width).

.container {
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-flow: row nowrap;
}

.col-1 {
    flex: 0 1 20rem;
    background-color: blue;
}

.col-2 {
    flex: 1 0 0;
    background-color: red;
}
<div class='container'>
    <div class='col-1'></div>
    <div class='col-2'></div>
</div>
  • Related