'Span use max width before line break
I've got following setup:
.container1 {
position: absolute;
max-width: 300px
}
.container {
position: absolute;
}
<div class="container">
<div class="container1">
<span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras dignissim purus et arcu ultrices posuere. Quisque tempus elementum facilisis. Duis vitae enim eu erat elementum dapibus vitae ac eros. Pellentesque faucibus pretium leo in accumsan. Nulla ullamcorper mollis dolor, euismod.
</span>
</div>
</div>
For some reason I can't get the span to grow to the defined 300px max-width while breaking once the max-width is reached.
Solution 1:[1]
In such case, use a big negative margin
.container1 {
position: absolute;
max-width: 300px;
margin-right:-100vmax
}
.container {
position: absolute;
}
<div class="container">
<div class="container1">
<span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras dignissim purus et arcu ultrices posuere. Quisque tempus elementum facilisis. Duis vitae enim eu erat elementum dapibus vitae ac eros. Pellentesque faucibus pretium leo in accumsan. Nulla ullamcorper mollis dolor, euismod.
</span>
</div>
</div>
Related to understand what is happening in your case: Why everything word-wrap inside an absolute element nested inside a float or inline-block element
Solution 2:[2]
Is applying position: absolute on container necessary?
When you use position: absolute without a parent element its positioned relative to, it will go out of the document flow. If you apply position: relative instead, the max-width behaviour will work as intended because its relative to the parent container container. By doing it like this, the element will stretch to full width (the max-width: 300px that you set) because its container doesnt have a specificed width
Read more about positioning values: https://developer.mozilla.org/en-US/docs/Web/CSS/position#types_of_positioning
.container1 {
position: absolute;
max-width: 300px;
}
.container {
position: relative;
}
<div class="container">
<div class="container1">
<span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras dignissim purus et arcu ultrices posuere. Quisque tempus elementum facilisis. Duis vitae enim eu erat elementum dapibus vitae ac eros. Pellentesque faucibus pretium leo in accumsan. Nulla ullamcorper mollis dolor, euismod.
</span>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Temani Afif |
| Solution 2 |
