How can I achieve the correct behavior of the element? The use of flex is optional, it can be grid or any other HTML code that gives the same result.
In my code, I have an element like this. These are the two flex items in the container: screenshot1
If the container's width decreases during resizing, it should look like this: screenshot2 That is, the text has become two-line, and the indent between the icon and the longest word of the text remains the same.
This is wrong because there is extra space between the text and the icon: screenshot3 This is what my code example gives.
Here is an example code:
<head>
<style>
.container{padding: 0 10px 0 10px;display:flex;align-items: center;height:50px;border: 1px solid #B6CBCF;overflow:hidden;}
.containerWidth{width:170px;}
.myText{width: fit-content;border-right: 1px solid #B6CBCF;}
.myIcon{width:36px;}
.iconImitation{width: 16px;height:16px;background-color:red;
border-radius: 50%;margin-left: 10px;}
</style>
</head>
<body>
<div class="container containerWidth">
<div class="myText">twoWordsContain Text</div>
<div class="myIcon"><div class="iconImitation"></div></div>
</div>
</body>
Here CodePen example
(same code).
For testing, you can change the .containerWidth
style: width:170px
or width:220px
. In the first case, the text will be two-line, in the second - single-line. The sizes are given for an example, in a real code I do not know them in advance.
For example, if I replace fit-content
with min-content
in the .myText
style, then in the narrow version, the elements will be positioned correctly. But in the wide version, the text will remain two-line, this should not happen. I also tried many other variations of the code to get the desired result.