Reputation: 5409
In the code snippet below, why does the inner content in Ex 1 overflow from the outer element, whereas in Ex 2, this does not occur? I'd expect both examples to either overflow or both to not overflow.
* {
box-sizing: border-box;
}
.outer {
border: 4px solid red;
width: 200px;
}
.inner {
border: 4px solid blue;
width: fit-content;
width: -moz-fit-content;
overflow-wrap: break-word;
max-width: 300px;
}
Ex 1
<div class="outer">
<div class="inner">
kasdhakjsdhaksjdhjhgjhgjhgjhgjhgjhgjhghj
</div>
</div>
<br />
Ex 2
<div class="outer">
<div class="inner">
asd asd asd asd asd asd asd asd asd asd asd
</div>
</div>
<br />
Ex 3
<div class="outer">
<div class="inner">
asd asd asd
</div>
</div>
Upvotes: 0
Views: 5066
Reputation: 272901
an inline-block
configuration can easily do it:
* {
box-sizing: border-box;
}
.outer {
border: 4px solid red;
width: 200px;
}
.inner {
border: 4px solid blue;
display:inline-block;
overflow-wrap: break-word;
max-width: 100%;
}
Ex 1
<div class="outer">
<div class="inner">
kasdhakjsdhaksjdhjhgjhgjhgjhgjhgjhgjhghj
</div>
</div>
<br />
Ex 2
<div class="outer">
<div class="inner">
asd asd asd asd asd asd asd asd asd asd asd
</div>
</div>
<br />
Ex 3
<div class="outer">
<div class="inner">
asd asd asd
</div>
</div>
Upvotes: 0
Reputation: 25392
width: fit-content
forces the width of the container to, well, fit the content, up to the limit of max-content
. Word breaks only occur if the content cannot fit within its container, but since the container is basically unbounded, the word doesn't wrap. You can see this if you set overflow: hidden
on the outer container.
From Mozilla:
The max-content sizing keyword represents the intrinsic maximum width of the content. For text content this means that the content will not wrap at all even if it causes overflows.
* {
box-sizing: border-box;
}
.outer {
border: 4px solid red;
width: 200px;
overflow: hidden;
}
.inner {
border: 4px solid blue;
width: fit-content;
width: -moz-fit-content;
overflow-wrap: break-word;
max-width: 300px;
}
Ex 1
<div class="outer">
<div class="inner">
kasdhakjsdhaksjdhjhgjhgjhgjhgjhgjhgjhghj
</div>
</div>
<br />
Ex 2
<div class="outer">
<div class="inner">
asd asd asd asd asd asd asd asd asd asd asd
</div>
</div>
<br />
Ex 3
<div class="outer">
<div class="inner">
asd asd asd
</div>
</div>
You can fix this by adding word-break as well, to force the words to break when they hit the edge of the container.
* {
box-sizing: border-box;
}
.outer {
border: 4px solid red;
width: 200px;
overflow: hidden;
}
.inner {
border: 4px solid blue;
width: fit-content;
width: -moz-fit-content;
overflow-wrap: break-word;
max-width: 300px;
word-break: break-word;
}
Ex 1
<div class="outer">
<div class="inner">
kasdhakjsdhaksjdhjhgjhgjhgjhgjhgjhgjhghj
</div>
</div>
<br />
Ex 2
<div class="outer">
<div class="inner">
asd asd asd asd asd asd asd asd asd asd asd
</div>
</div>
<br />
Ex 3
<div class="outer">
<div class="inner">
asd asd asd
</div>
</div>
Upvotes: 5