I have a parent
container with a fixed size, and absolutely positioned child
divs inside it. The position of the child divs have dynamic text content a
Don't use left
to position the element but consider translate instead. The left property will restrict the width of your element.
/* Relevant parent and child styles */
.parent {
position: relative;
width: 500px;
height: 400px;
}
.child {
position: absolute;
max-width: 250px;
}
/* Individual positioning of child elements */
#fine {
top: 30px;
transform: translateX(100px);
}
#wrapped {
top: 90px;
transform: translateX(400px);
}
#unwrapped {
top: 200px;
left: 170px;
}
#extra {
top: 300px;
left: 170px;
}
/* The rest is only styles to make the example easier on the eye */
body {
background-color: hsl(0, 0%, 90%);
margin: 0;
padding: 24px;
}
.parent {
background-color: white;
border: 2px solid grey;
}
.child {
padding: 12px;
background: yellowgreen;
}
<div class="parent">
<div id="fine" class="child">
Text should be wrapped normally with the max-width of the child, like this
</div>
<div id="wrapped" class="child">
This text will be wrapped much earlier though because it is running out of the parent container
</div>
<div id="unwrapped" class="child">
"white-space: nowrap" only prevents *all* wrapping
</div>
<div id="extra" class="child">
short text
</div>
</div>
Or consider a big negative margin (at least equal to max-width
) to negate the use of left:
/* Relevant parent and child styles */
.parent {
position: relative;
width: 500px;
height: 400px;
}
.child {
position: absolute;
max-width: 250px;
margin-right:-250px;
}
/* Individual positioning of child elements */
#fine {
top: 30px;
left:100px;
}
#wrapped {
top: 90px;
left: 400px;
}
#unwrapped {
top: 200px;
left: 170px;
}
#extra {
top: 300px;
left: 170px;
}
/* The rest is only styles to make the example easier on the eye */
body {
background-color: hsl(0, 0%, 90%);
margin: 0;
padding: 24px;
}
.parent {
background-color: white;
border: 2px solid grey;
}
.child {
padding: 12px;
background: yellowgreen;
}
<div class="parent">
<div id="fine" class="child">
Text should be wrapped normally with the max-width of the child, like this
</div>
<div id="wrapped" class="child">
This text will be wrapped much earlier though because it is running out of the parent container
</div>
<div id="unwrapped" class="child">
"white-space: nowrap" only prevents *all* wrapping
</div>
<div id="extra" class="child">
short text
</div>
</div>
To understand how both tricks work you need to refer to the specification where you can find the formula to calculate the width of your element:
The constraint that determines the used values for these elements is:
'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block
You can then read the different case where some values are specified and other auto