0

I have the following html/css. Which renders like this:

.parent {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}

.one {
  flex: 1;
  background-color: green;
}

.two {
  flex: 1;
  /* width: 100px; <-- this is what I'd like to achieve */
  background-color: yellow;
}

.inner {
  width: 150px; /* <-- this is bigger than width of .parent */
  height: 50px;
  background-color: blue;
}
<div class="parent">
  <div class="one"></div>
  <div class="two">
    <div class="inner"></div>
  </div>
</div>

enter image description here

As you can see the div with .inner is 150px causing its parent div, with flex: 1, to take more space.

What I'd like to achieve is this:

enter image description here

I know the existence and tried to use, flex-grow and flex-shrink. I couldn't make it work.

The question: is there a way to make it work using only flexbox?

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Besart Hoxhaj
  • 917
  • 1
  • 8
  • 12

1 Answers1

0

Easily managed with position: relative one two and position:absolute on inner

.parent {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}

.one {
  flex: 1;
  background-color: green;
}

.two {
  position: relative;
  flex: 1;
  /* width: 100px; <-- this is what I'd like to achieve */
  background-color: yellow;
}

.inner {
  position:absolute;
  width: 150px; /* <-- this is bigger than width of .parent */
  height: 50px;
  background-color: blue;
}
<div class="parent">
  <div class="one"></div>
  <div class="two">
    <div class="inner"></div>
  </div>
</div>

Only using max-width:50% on class two

DEMO 2

.parent {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}

.one {
  flex: 1;
  background-color: green;
}

.two {
  flex: 1;
  max-width: 50%;
  /* width: 100px; <-- this is what I'd like to achieve */
  background-color: yellow;
}

.inner {
  width: 150px; /* <-- this is bigger than width of .parent */
  height: 50px;
  background-color: blue;
}
<div class="parent">
  <div class="one"></div>
  <div class="two">
    <div class="inner"></div>
  </div>
</div>
MaxiGui
  • 6,190
  • 4
  • 16
  • 33
  • Thank you for the quick reply. However, is there a way to make it work using only flex-shrink/flex-grow? i.e. isn't shrink/grow meant for this kind of scenarios? – Besart Hoxhaj Nov 05 '20 at 18:10
  • Please check Demo 2, I made it just by adding: `max-width: 50%;` on class `two`. Just with flex, you wont be able – MaxiGui Nov 05 '20 at 18:20