Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading