CSS + Bootstrap: how to dynamically stretch the width of a subdiv to fit the container (with the image)?

I have a problem where I have a dynamic part of my page where I can have 1,2,3 or 4 subdivs (look at the pink arrows below). As you can see in the first section of facebook, divs are not stretched. I want it to be in the third. If there are only 2 of them, then they should be in half and occupy the entire width of the container.

How should I do it?

HTML:

<div class="channel-box">
  <div class="facebook-engagements">
    <img src='blah.img' title="Facebook" />
    <span class="small-stats-font">123</span>
  </div>
  <div class="channel-breakdown clearfix row-fluid">
    <div class="channel-units">
      <img src='blah.img' title="Post" />
      <span class="smaller-stats-font">123</span>
    </div>
    <div class="channel-units">
      <img src='blah.img' title="Like" />
      <span class="smaller-stats-font">123</span>
    </div>
    <div class="channel-units">
      <img src='blah.img' title="Share" />
      <span class="smaller-stats-font">
        123
      </span>
    </div>
  </div>
</div>

      

CSS

      .channel-breakdown {
        border-top: 1px solid gray;

        .channel-units {
          border-right: 1px solid gray;
          display: inline-block;
          float: left;
          margin-right: 10px;
          width: 23%;
        }
      }

      

enter image description here

+1


source to share


2 answers


CSS flexbox to the rescue! Flex is awesome and is supported by modern browsers .

.channel-breakdown {
  border-top: 1px solid gray;
  display: flex;

  .channel-units {
    border-right: 1px solid gray;
    margin-right: 10px;
    flex-grow: 1;
  }
}

      



"use strict";

document.addEventListener("click", function (e) {
  if (e.target.nodeName === "BUTTON") {
    let div = document.createElement("div");
    div.textContent = parseInt(Math.random() * 100, 10);
    
    document.querySelector(".flex").appendChild(div);
  } else if (/\bflex\b/.test(e.target.parentNode.className)) {
    e.target.remove();
  }
});
      

.flex div {
  text-align: center;
  border: 1px solid black;
  margin: 0;
  flex-grow: 1;
}

.flex {
  border: 1px solid black;
  display: flex;
}
      

<button>Click to add another div</button>
<p>Click on a box to remove it</p>

<div class="flex">
  <div>12</div>
  <div>34</div>
  <div>56</div>
</div>
      

Run codeHide result


+3


source


CSS tables are how I feel here.



   .channel-breakdown {
     border-top: 1px solid gray;
     display: table;
     table-layout: fixed;
     width: 100%;
   }
   .channel-units {
     border-right: 1px solid gray;
     display: table-cell;
   }
      

Run codeHide result


0


source







All Articles