I have an h3 element of which I don't know its width. Therefore the width is at auto
- the default. But I want the text inside of it to have hyphenation. It is in flex container together with a second element. The flex container has a fixed width. This works in all browsers, except for Safari. There the hyphenation simply doesn't work at all. The text overflows and pushes also the second element out of the wrapper. In Safari it only works when I set the width of the h3 element to a specific value, for example width: 300px
or width: 80%
, but as I already mentioned I can't do that. it also works when I remove the display: flex
, but I also don't want to do that.
Here's a short example to showcase the problem:
.card {
display: flex;
align-items: flex-start;
border: 1px solid #ddd;
width: 200px;
}
h3 {
flex: 1;
background: #ff5604;
hyphens: auto;
-webkit-hyphens: auto;
}
button {
display: inline-block;
}
<html lang="de">
<head>
</head>
<body>
<div class="card">
<h3>Versicherungsmaklerbüro/Versicherungsmaklerinnenbüro</h3>
<button>
Button
</button>
</div>
</body>
</html>
Is there a pure CSS way to make Safari behave?
The h3 element by default is a block level element. It means it has 100% width by default which is 100% width of the parent container, in You case it's 200px. That way the hyphenation will work properly as you expected, the content of the h3 obviously is bigger than 200px so as a result you will see the hyphens applied.
Now you set the .card element to be displayed as flexbox which means all the direct children become flex-items. The flex-item has different default properties, technically it's not a block level element anymore I guess. The flex-item's width by default equals to the length of the content. Initially it does not care about the parent element's width. So 200px does not help here. In order to make the flex-item take the 100% width of the parent element you have to specify it directly. In your case you must tell the element to use width: 100% to force it break the content and fit the parent container space.
Flex items sizing follow this specific formula: content —> width —> flex-basis. More details see in this great article.
As you see it's not actually a Safari bug but an unexpected result of rules/combination of rules you use.