I have headings that have display:inline-block
set, but one of them is really long and takes two lines. The issue is that when it breaks to the second line, it automatically makes it take the whole width of the parent container (even though it has plenty of space around it, and it is set to inline-block).
Anyone knows how to prevent this? Also, I can't really use a solution that only applies to this one if it will break other headings, because the same code is generating other 9 non-line-breaking headings using the same structure.
Thank you for your time.
CodePen: https://codepen.io/anon/pen/gGdYmB#anon-signup
<div id="parent1" class="parent">
<h2>SHORT HEADING</h2>
<h2>THE REALLY LONG HEADING THAT
<span>BREAKS TO A SECOND LINE</span></h2>
</div>
<style>
.parent {
width:50vw;
background-color:#046;
height:20vw;
text-align:center;
}
.parent h2 {
display:inline-block;
color:#fff;
font-family:sans-serif;
font-weight:900;
font-size:2vw;
background-color:#28a;
padding:10px 0;
}
.parent h2 span {
display:inline-block
}
</style>
By default, an inline-block will get pushed to the second line unless the entire element can fit on the first line. The whole group of words are a single element and are trying to be inserted into your header directly to the right of the word "That". Because the words as a group are bigger than what can fit on the first line, it puts them all on the next line, but only after expanding the parent (your h2) trying to accommodate it.
If you're ok with the text in span breaking to a new line: Have your span display as block instead of inline-block, or switch to div instead of span. This will ensure that the text goes to a new line without first trying to expand your parent horizontally. Since an inline-block in this situation is probably going to have a line break anyways, why not do it this way?
If you want to make sure that the span doesn't break: Then you can't style it as Inline-block or block. Inline-block won't break only as long as it's width is small enough. Don't set the display (in span) at all and your header will wrap the text and take up the entire width available. Then add a small left/right margin to your header, as the most wasted space you'll have is the width of your longest word being pushed to the next line.