1

There is a parent div with 2 children - child1 and child2.

<div class="parent">
    <div class="child1"></div>
    <div class="child2">
        <p>Some long text...</p>
    </div>
</div>

I want the parent to expand it's width by the child1 div (e.g. if child1 has width=200px, parent has the same width).

Below child1, there should be the child2 div and fill 100% of the parent's width (set by child1), but not expand the parent's width further (e.g. if there is a long paragraph of text, it should wrap on 200px).

How can I achieve this with CSS?

KadlinoBIT
  • 27
  • 6

1 Answers1

2

You need to set min-content on your parent's max-width. This will reduce the maximum width to the smallest word it can fit. Then you set the width of your first child to max-content in order to force the parent to expand to this set width.

.parent {
  max-width: min-content;
}

.child1 {
  width: max-content;
}
<div class="parent">
    <div class="child1">The width should stop here</div>
    <div class="child2">
        <p>Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text Some long text </p>
    </div>
</div>
dreamLo
  • 1,612
  • 12
  • 17
  • 1
    I'm not sure why this question was closed as duplicate. The solution in the duplicated answer offers a hack with inline-block and width zero. My solution has no hacks and works as intended in all modern browsers. – dreamLo Jul 15 '21 at 09:37
  • I'm with you, checked the other solution and yours is so much clearer. – KadlinoBIT Jul 15 '21 at 11:13