Search code examples
htmlcssreactjsflexboxcss-grid

Make text overflow according to width of top sibling text


I would like to solve this with CSS only (if possible) and can't seem to find the solution. Let's say I have a simple component as such:

<div class='container'>
    <h1 class='title'>This is a long title</h1>
    <div class='subtitle'>explanation with width longer than the title</div>
</div>

Which renders something like this (assuming the container is a column flexbox):

This is a long title
explanation with width longer than the title

I would like it to render:

This is a long title
explanation with
width longer than
the title

I need the second child element's max-width to match the width of the title element. Is there a way to do this with flex or grid?


Solution

  • You can achieve that by following:

    <div class='container'>
        <h1 class='title'>This is a long title</h1>
        <span class='subtitle'>explanation with width longer than the title text</span>
    </div>
    
    .title {
      width: fit-content;
      display: inline-block;
    }
    
    .subtitle {
      position: static;
      white-space: break-spaces;
    }
    
    .container {
      display: flex;
      flex-direction: column;
      width: min-content;
      white-space: nowrap;
      position: relative;
    }
    

    Working demo: https://codepen.io/wajeshubham/pen/vYzBRej