IamGrooot
IamGrooot

Reputation: 1040

how to restrict horizontal strech of css flex

I am having a div with 3 child divs. I am using CSS flex for dynamically set the height of div. With 3 divs it's working fine.

But there may be a scenario where I will be having 2 child divs. Here child divs are stretching and taking full width of the page. How can I restrict this stretch using only CSS. Check its behaviour by removing div 3.

html, body {
    height: 100%;
}

body {
    margin: 0;
}

.flex-container .row {
    display: flex;
}

.flex-item {
    flex: 1;
    display: inline-block;
    background: yellow;
    margin: 10px;
    height: 100px;
}
<div class="flex-container">
    <div class="row"> 
        <div class="flex-item">DIV 1</div>
        <div class="flex-item">DIV 2</div>
        <div class="flex-item">DIV 3</div>
    </div>
</div>

2 child divs streching like this

2 divs stretching taking entire width

Upvotes: 0

Views: 166

Answers (1)

Asons
Asons

Reputation: 87251

Using flex-basis might be an option

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
.flex-container .row {
  display: flex;
}
.flex-item {
  flex-basis: calc(33.33% - 20px);
  background: yellow;
  margin: 10px;
  height: 100px;
}
<div class="flex-container">
  <div class="row">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="flex-item">3</div>
  </div>
</div>

<div class="flex-container">
  <div class="row">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
  </div>
</div>


Another option is to set flex-grow to a number smaller than 1

So i.e. achieve the same result as with flex-basis, you need to set flex-shrink to 0 and add an extra element inside the flex items to handle the margin's.

html,
body {
  height: 100%;
}
body {
  margin: 0;
}
.flex-container .row {
  display: flex;
}
.flex-item {
  flex: 0.333 0;
} 
.flex-item div {
  background: yellow;
  margin: 10px;
  height: 100px;
}
<div class="flex-container">
  <div class="row">
    <div class="flex-item"><div>1</div></div>
    <div class="flex-item"><div>2</div></div>
    <div class="flex-item"><div>3</div></div>
  </div>
</div>

<div class="flex-container">
  <div class="row">
    <div class="flex-item"><div>1</div></div>
    <div class="flex-item"><div>2</div></div>
  </div>
</div>

Upvotes: 1

Related Questions