0

I have a div container with multiple children (also divs). I need the bottom child to be the same width as the text inside it. The parent container and the other children should have exactly the same width as the bottom child has, i.e. the bottom child determines the width of everything. How do I achieve that?

I suspected that flexbox might help, but I wasn't able to find anything related in the documentation. Is it even possible to do it in pure CSS or I have to use JavaScript for that?

Here is a fiddle that demonstrates the problem.

<div class="parent">
  <div class="slave">Child that shouldn't dictate the width to anybody at all even though it's long</div>
  <br>
  <div class="master">Child that dictates the width to the parent and siblings</div>
</div>

What it does:

enter image description here

What I would like (ellipsis is unnecessary, it's fine if it just cuts off):

enter image description here

Roman Petrenko
  • 1,052
  • 1
  • 9
  • 21

2 Answers2

1

Wrap text of the slave by div and place it absolute. To add tree dots when text is too long apply text-overflow: ellipsis.

.parent {
  background-color: green;
  display: inline-block;
}

.slave {
  background-color: blue;
  color: red;
  width: auto;
  height: 40px;
  position: relative;
}

.slave div {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;

  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.master {
  background-color: red;
  color: black;
  width: auto;
  height: 40px;
}
<div class="parent">
  <div class="slave">
    <div>Child that shouldn't dictate the width to anybody at all even though it's long</div>
  </div>
  <br>
  <div class="master">Child that dictates the width to the parent and siblings</div>
</div>


<div class="parent">
  <div class="slave">
    <div>Two words</div>
  </div>
  <br>
  <div class="master">Child that dictates the width to the parent and siblings</div>
</div>
3rdthemagical
  • 5,271
  • 18
  • 36
0
div {
  white-space: nowrap; 
  overflow: hidden;
  text-overflow: ellipsis;
}

Hope this will be the solution for your problem

Udayavani
  • 306
  • 2
  • 9