Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making three divs fit perfectly in a parent div

Tags:

html

css

width

I have been building websites for way too long not to know how to do this. I'm embarrassed to ask. But I must.


I want a way to make any number of child divs within a parent div automatically span to the full width of the parent div.

My criteria for this fix are:

  1. All of the child divs must be the exact same width
  2. The width of the children divs must be responsive/dynamic
  3. I would prefer a fix that doesn't involve sitting there and testing different percentages to find the exact percent width to prevent one of the children being wrapped or hidden (IE "display: if-there-was-an-easy-fix" instead of "width: 29.468749%")
  4. I would love it if the fix would work with fixed margins and dynamic margins (margin: 10px and margin: 5%)

I'm 99% sure I knew the answer to this like a year ago but my current job requires that I work almost exclusively in tables, so I've forgotten how to do anything that isn't clunky and semantically disgusting.

#wrap {
  width: 100%;
  max-width: 500px;
  background-color: gray;
  height: 200px;
  display: block;
}

.box {
  width: 29.468749%;
  height: 200px;
  display: inline-block;
  margin: 0;
  padding: 0;
  border: none;
}

#one {
  background-color: aliceblue;
}

#two {
  margin: 0 5%;
  background-color: wheat;
}

#three {
  background-color: coral;
}
<div id="wrap">
  <div class="box" id="one">
  </div>
  <div class="box" id="two">
  </div>
  <div class="box" id="three">
  </div>
</div>
like image 287
S. Ling Avatar asked Oct 12 '25 09:10

S. Ling


1 Answers

use display: flex on parent and flex: 1 on child elements to get flexbox

#wrap {
  width: 100%;
  max-width: 500px;
  background-color: gray;
  height: 200px;
  /*display:block;*/
  display: flex;
}

.box {
  /*width: 29.468749%;*/
  /*display:inline-block;
    /*margin:0;
    padding:0;*/
  flex: 1;
  height: 200px;
  border: none;
}

#one {
  background-color: aliceblue;
}

#two {
  margin: 0 5%;
  background-color: wheat;
}

#three {
  background-color: coral;
}
<div id="wrap">
  <div class="box" id="one">
  </div>
  <div class="box" id="two">
  </div>
  <div class="box" id="three">
  </div>
</div>
like image 191
whitehat Avatar answered Oct 13 '25 21:10

whitehat