I’m struggling with a Flexbox layout issue where I want a specific wrapping behavior for words inside a <span>
classed as keep-together
. The requirement is for the words to stay together on the same line as much as possible, wrapping to a new line only when the container is too narrow to fit them side by side.
Here is the CSS I’m currently using for the .keep-together
:
.keep-together {
display: inline-flex;
flex-flow: row wrap;
background-color: #ffd700; /* visual aid to see the span */
overflow-wrap: anywhere;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Text Wrapping with Container Queries</title>
<style>
.container {
border: 2px solid #000;
padding: 10px;
resize: both; /* allows you to resize the container in the browser for testing */
overflow: auto;
width: 50%; /* initial width, adjustable for testing */
margin: 20px auto; /* centering the container */
}
.keep-together {
display: inline-flex;
flex-flow: row wrap;
background-color: #ffd700; /* visual aid to see the span */
overflow-wrap: anywhere;
}
.keep-together > span{
background-color: blue;
}
</style>
</head>
<body>
<div class="container">
<p class="text">Watch how <span class="keep-together">
<span>word1</span>
<span>word2</span>
<span>word3</span>
</span>
wrap based on container size.
</p>
</div>
</body>
</html>
Desired Behavior:
- The words within the
keep-together
should stay on the same line under normal conditions, even when that means moving all words together to a new line. - Only if the container’s width is so small that all words cannot fit on a single line at all, should they break into separate lines.
- Each word should only take up as much width as necessary when wrapped onto separate lines, and their container should not expand to fill the entire avaialble space.
Current Issue:
Currently, when the container’s width forces the words to wrap, the container stretches to occupy the full width of the available space, which is not desired. I need the words to wrap together to a new line however follow up content should also appear on the same line as the wrapped word and not on a separate line.
Attempts to Resolve:
I have also tried using display: inline-block
. Both attempts, however, have led to the words expanding to fill the full container width upon wrapping, which is not the desired outcome.
I am looking for a pure CSS solution that can facilitate this nuanced wrapping behavior. Does anyone have suggestions or insights on how to adjust CSS Flexbox or other properties to achieve this behavior?
Thank you in advance for your help and insights!
5