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

CSS fit-content does not fit the real content when there is a line break

I have a fixed container (20em) in row direction. In this container, I would like to have 3 items:

  1. An item containing a text (dish name)
  2. An item taking the remaining space with a minimum of 10% of the main container (link between dish name and price)
  3. An item containing a text (dish price)

In HTML/CSS:

<div class="container">
  <div class="dish">Creamy Mushroom Risotto with Parmesan</div>
  <div class="dots"></div>
  <div class="price">$12.25</div>
</div>
.container {
  display: flex;
  flex-direction: row;
  width: 20em;
  border: 1px solid black;
}

.dish {
  width: fit-content;
}

.dots {
  margin-top: 1em;
  border-top: 1px dotted black;
  min-width: 10%;
  flex-grow: 1;
}

It works well, except when the first item has a line break. In this case, the second item does not take all the remaining space:
description in post

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

https://jsfiddle.net/ptmka1c3/1/

What are my options to get what I want?

>Solution :

Yes, text nodes does not align the text to the minimun depending on the text-align property

You could try to set text-align: justify or try the 2nd option of this answer

.container {
  display: flex;
  flex-direction: row;
  width: 20em;
  border: 1px solid black;
}

.dish {
  text-align: justify;
}

.dots {
  margin-top: 1em;
  border-top: 1px dotted black;
  min-width: 10%;
  flex-grow: 1;
} 
<div class="container">
  <div class="dish">Creamy Mushroom Risotto with Parmesan</div>
  <div class="dots"></div>
  <div class="price">$12.25</div>
</div>

Edit: Option 2:

Usa different layer for text and dots, and insert the text into a inline element:

.container {
  display: flex;
  flex-direction: row;
  width: 20em;
  border: 1px solid black;
  position: relative;
}

.dots {
  top: 1em;
  border-top: 1px dotted black;
  position: absolute;
  z-index: 1;
  width: 100%;
}

.price,
.dish {
  position: relative;
  z-index: 2;
}

.dish .text {
  display: inline;
  background-color: white;
}

.price {
  margin-left: 1.5rem;
  background-color: white;
}
<div class="container">
  <div class="dish">
  <span class="text">Creamy Mushroom Risotto with Parmesan</span></div>
  <div class="dots"></div>
  <div class="price">$12.25</div>
</div>
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