How to prevent a div with flex display shrinks the child elements?

Asked

Viewed 76 times

2

I made the following example code:

.container {
  width: 200px;
  height: 50px;
  background-color: #f00;
  display: flex;
  flex-direction: row;
  overflow-x: scroll;
}

.div1 {
  width: 150px;
  background-color: #0f0;
}

.div2 {
  width: 150px;
  background-color: #00f;
}
<div class="container">
  <div class="div1">150px</div>
  <div class="div2">150px</div>
</div>

Note that I have a div "container" with 200px wide and inside two other Divs with 150px wide and need to have a scroll bar in the container div. It turns out that even setting the width of 150px to "div1" and "div2", the Divs "shrunk" to fit in 200px as per the image:

inserir a descrição da imagem aqui

How to stop it from happening?

2 answers

3

After asking the question I continued to do some tests and managed to solve the "problem".

Just set the property flex-shrink: 0; in the child elements:

.container {
    width: 200px;
    height: 50px;
    background-color: #f00;
    display: flex;
    flex-direction: row;
    overflow-x: scroll;
}
.div1{
    width:150px;
    background-color: #0f0;
    flex-shrink: 0;
}
.div2{
    width:150px;
    background-color: #00f;
    flex-shrink: 0;
}
<div class="container">
    <div class="div1">150px</div>
    <div class="div2">150px</div>
</div>

So I got the expected result:

inserir a descrição da imagem aqui

I’ll put the solution on record in case anyone else has the same doubt.

2

Tried to use the min-width for both divs? This prevents the divs decrease below the limit and causes the scroll horizontal.

See below:

.container {
    width: 200px;
    height: 50px;
    background-color: #f00;
    display: flex;
    flex-direction: row;
    overflow-x: scroll;
}
.div1{
    min-width:150px;
    background-color: #0f0;
}
.div2{
    min-width:150px;
    background-color: #00f;
}
<div class="container">
    <div class="div1">150px</div>
    <div class="div2">150px</div>
</div>

  • 1

    I kept testing and managed to solve using flex-Shrink: 0; in the child elements, but thank you for the suggestion too!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.