Skip to content Skip to sidebar Skip to footer

Keep Heading (h1, H2...) From Going Full Width On Line Break

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

Solution 1:

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.

Solution 2:

You could set max-width: 80%; on your .parent h2 css (line 7) to get the desired result

Solution 3:

You can set a max-width. See example below:

.parent {
  width:50vw;
  background-color:#046;
  height:20vw;
  text-align:center;
}
.parenth2 {
  display:inline-block;
  color:#fff;
  font-family:sans-serif;
  font-weight:900;
  font-size:2vw;
  background-color:#28a;
  padding:10px0;
  max-width: 45vw; /* 5vw smaller then your parent width, which is 50vw */
}
.parenth2span {display:inline-block}
<divid="parent1"class="parent"><h2>SHORT HEADING</h2><h2>THE REALLY LONG HEADING THAT <span>BREAKS TO A SECOND LINE</span></h2></div>

Post a Comment for "Keep Heading (h1, H2...) From Going Full Width On Line Break"