3

Is there any way to get all children of a parent to be the same width without having the parent be a block level element?

Basically I want all the "columns" in the jsfiddle to have the same width but I don't want the container to span the entire width of the container, only the necessary width.

Edit: I am looking for a way to handle a dynamic number of children

Edit2: Updated the fiddle and code to make widths more obvious

Thanks!

HTML

<div class="container">
  <div>
  Short
  </div>
  <div>
  SomethingSuperLong
  </div>
  <div>
  Ok
  </div>
</div>

https://jsfiddle.net/0g9af1dh/2

noveyak
  • 3,240
  • 1
  • 19
  • 19

5 Answers5

1

Check the below snippet.

var maxWidth = 0;
$('.container > div').each(function() {
  var thisWidth = $(this).outerWidth();
  if(maxWidth < thisWidth) {
    maxWidth  = thisWidth;
  }
});
$('.container > div').width(maxWidth);
.container {
  display: inline-flex;
}

.container > div {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container">
  <div>
    Short
  </div>
  <div>
    Something super long
  </div>
  <div>
    Ok
  </div>
</div>

Edit: May be if you are open for script as well. Neglect otherwise.

Charan Kumar
  • 553
  • 2
  • 13
1

So, the capabilities of flex, but with inline behavior? Hmmm...

.container {
  display: inline-flex;
}

.container > div {
  flex: 1 0 0;
  border: 1px solid red;
}
<div class="container">
  <div>
  Short
  </div>
  <div>
  Something super long
  </div>
  <div>
  Ok
  </div>
</div>
Noah
  • 1,329
  • 11
  • 21
  • Updated the fiddle to make it more obvious. If you use inspector you will notice those 3 columns are not the same width. I made SomethingSuperLong one word to make it a bit clearer for other people experimenting – noveyak Jun 17 '16 at 06:32
0

Well if you just want them to be the same size you can do it like this.

.container > div {
width: 33.3%;
}

If it's not what you want, tell me in the comments and I will update it.

Frutis
  • 489
  • 3
  • 16
0

just change your css to

.container {
  display: flex;
}

.container > div {
  flex:1;
  border: 1px solid red;
}
Hiral Suvagya
  • 591
  • 3
  • 8
0

my solution is very similar to this solution

But in his solution he left them as display: table which makes the outer div share qualities of display: block

If you change it to use display: inline-table it takes on inline characters. To show that it is inline I placed test inline next to the outer div.

This solution does require you set a width for your outer container. Based on your question details I think this works for you but if it doesn't let me know and I can tweak the answer.

Community
  • 1
  • 1
T.Okahara
  • 1,184
  • 2
  • 14
  • 27