Sebastian Olsen
Sebastian Olsen

Reputation: 10878

3 dynamic divs inside a parent div with fixed size

I'm having some trouble here, I am trying to create three divs with varying width inside a parent div of fixed width. Is there anyway to have the divs adjust themselves based on how much space is in there? basically all three divs will have varying size and needs to fill the parent div. The divs also need to be on the same line. Height is not an issue.

Something like this:

<div id="parent">
  <div></div>
  <div></div>
  <div></div>
</div>

Upvotes: 0

Views: 858

Answers (4)

Hatchet
Hatchet

Reputation: 5428

Flexbox to the rescue!

For this example, I used justify-content: space-between, but there are a lot of different options.

Wonderful overview of flexbox

#parent {
  width: 300px;
  background-color: orange;
  display: flex;
  justify-content: space-between;
}

.grow {
  flex-grow: 1;
  background-color: yellow;
}
<div id="parent">
  <div>One</div>
  <div class="grow">Two</div>
  <div>Three</div>
</div>

Upvotes: 3

Omar Yafer
Omar Yafer

Reputation: 853

How about doung it like this.

div#parent{
  border: 1px solid gray;
  width: 400px;
  margin: 0 auto;
  height: 200px;
  padding: 0;
}
div#parent > div{
  border: 1px solid gray;
  width: 32%;
  margin: 5px auto;
  display: inline-block;
  height: 150px;
}
<div id="parent">
  <div></div>
  <div></div>
  <div></div>
</div>

Upvotes: 0

J. Bush
J. Bush

Reputation: 358

There are several ways to do this. The easiest would probably be:

#parent {
    display: table-row;
}
#parent div {
    display: table-cell;
}

This will cause the elements to behave like an HTML table. (you could also just use a table to make things easier).

Upvotes: 2

Tennyson H
Tennyson H

Reputation: 1716

You can use some CSS rules to achieve the behavior you are describing. Here is a fiddle: https://jsfiddle.net/sfmj4ca8/1/

  • max-width: 33%; ensures that the 3 divs will at most take up 99% width
  • display: inline-block; makes the divs appear inline.

Upvotes: 0

Related Questions