James
James

Reputation: 323

Equal divs depending on width?

How can I display different number of divs? For example the first section has three divs, the second section has two.

But they need to be the same width - so the divs always fill the section, regardless of how many divs are there.

DIV -- DIV -- DIV
DIV --------- DIV

I think I need to use max width? Is that right?

section {
  width: 960px;
  background: grey;
}

div {
  display: inline-block;
  margin: 0;
  height: 200px;
  background: black;
  width: 33%;
}
<section>
<div></div>
<div></div>
<div></div>
</section>

<section>
<div></div>
<div></div>
</section>

Upvotes: 1

Views: 60

Answers (3)

G-Cyrillus
G-Cyrillus

Reputation: 105893

flex will manage this perfectly from a single section via flex if wrap is set and min-width to tune max numbers of div on each rows

section {
  width: 960px;
  background: grey;
  display:flex;
  flex-wrap:wrap;
  justify-content:space-between;
  padding:3px;/* equals, to fit children margins value */
}

div {
  display: inline-block;
  margin:3px ;
  height: 200px;/* can be be min-height or removed to let tallest div to set row's height */
  background: black;
  min-width: 32%;
  flex:1;
}
.ha div {
height : auto;
color:white;
padding:1em;
}
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
<hr/>
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
<hr/>
<section class="ha">
<div> hi <i>(let's height be)</i></div>
<div> the<br/>world</div>
</section>

Upvotes: 1

Michael Coker
Michael Coker

Reputation: 53674

You can use display: table on the parent, and display: table-cell on the children.

section {
  display: table;
  margin: 0 0 1em;
  width: 100%;
}
section > div {
  display: table-cell;
  background: #eee;
  border: 1px solid #aaa;
  height: 1em;
}
<section>
  <div></div>
  <div></div>
  <div></div>
</section>

<section>
  <div></div>
  <div></div>
</section>

Upvotes: 2

roberto tom&#225;s
roberto tom&#225;s

Reputation: 4687

section {
  width: 960px;
  background: grey;
display: flex;
}

div {
  display: inline-block;
  height: 200px;
  background: black;
flex: 1 1 auto;
margin: 0 1rem;
}
<section>
<div></div>
<div></div>
<div></div>
</section>

<section>
<div></div>
<div></div>
</section>

Upvotes: 2

Related Questions