How to adjust divs to decrease their size as you add new sister divs?

Viewed 47

I need a parent div to occupy the entire width of the screen and when adding child divs inside the parent div, the child divs will decrease the width so that they all fit inside the parent div without having scrool. Equal behavior of browsers when adding new tabs.tabs

3 Answers

One easy way to do this is with display: table. It works in current modern browsers.

#wrapper {
  display: table;
  table-layout: fixed;
  width: 100%;
  height: 100px;
}

#wrapper div {
  display: table-cell;
  height: 100px;
}
#one {
  background-color:green
}
#two {
  background-color:blue
}
#three {
  background-color:red
}
<div id="wrapper">
  <div id="one">one one one one one one one one one one one one one one one one one one one one one</div>
  <div id="two">two two two two two two</div>
  <div id="three">three</div> 
</div>

Example : http://jsfiddle.net/dokve351/

Just use display: flex; on the container. The default flex-shrink will handle the rest:

document.querySelector('button').addEventListener('click', function() {
  const div = document.createElement("div");
  document.querySelector('.container').appendChild(div);
});
.container {
  display: flex;
}

/* for visualization only */
.container {
  border: 2px dashed red;
  height: 50px;
}

.container > div {
  width: 100px;
  border: 3px solid blue;
}
<div class="container"></div>
<button>Click me to add an Element</button>

You can try

.parent{
display : flex-shrink;
}
.child{
width : auto
max-width : 100px;
min-width : 10%;
}

Thats with basic CSS, if you are using React there will be an easier code.

Related