Quantcast
Channel: Active questions tagged flexbox - Stack Overflow
Viewing all articles
Browse latest Browse all 1671

Two dynamic strings space distribution with CSS

$
0
0

Frontend newby here - got this task with 2 dynamic strings, one goes next to the other horizontally in a fix width container, one string aligned to the left, the other - to the right.Feels like there is a simple solution that I'm missing out.

Rules how to distribute space between them are as follows:

  1. Both strings take as much space as they need if their total width not exceeds the container's.
  2. If both strings are longer than the half of the container they should take 50% and be truncated with ellipsis
  3. If one string is shorter than 50% and the other is longer, the shorter string should take up as much space as it needs, and the longer string should take up the remaining available space (but be truncated with ellipsis if it exceeds that space).

So all that falls into 4 cases: two shorts, two long, left shorter, right one is shorter. (probably, two more when one of them is longer than half of container, but together they are not longer than container, so neither gets truncated)

So far I managed to make them behave as on this image

However I can't beat that in cases 2 and 3 the shorter string gets cut off, although it shouldn't

Here are the classes for left and right strings:

.container {  display: flex;  width: 600px;  gap: 10px;  max-width: 100%;  margin-bottom: 10px; /* Add margin between each case */}.text {  white-space: nowrap; /* Prevent text from wrapping */  overflow: hidden; /* Hide overflowing text */  text-overflow: ellipsis; /* Add ellipsis (...) for overflowed text */  padding: 5px;  min-width: 0; /* Allow shrinking */  border: 1px solid #ccc;  border-radius: 5px;}/* Left text */.left {  flex-shrink: 1; /* Allow the left text to shrink if necessary */  max-width: 100%; /* Allow it to take up as much space as it needs */  margin-right: auto;  background-color: red;}/* Right text */.right {  flex-shrink: 1; /* Allow the right text to shrink if necessary */  margin-left: auto; /* Push the right text to the right */  max-width: 100%; /* Allow it to take up as much space as it needs */  background-color: green;}

And a case looks like this:

<div class="container"><div class="text left">Short text on the left side</div><div class="text right">This is a very long text that will take up the remaining space and will be truncated if it overflows.</div></div>

Here is the full code I got to achieve this: https://jsfiddle.net/k6jfpyrh

Any help appreciated


Viewing all articles
Browse latest Browse all 1671

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>