bakerkretzmar bakerkretzmar - 1 month ago 5
HTML Question

Heading won't align center if longer than one line

I have a header with a title and subtitle that are both center aligned using flexbox, and have a pale white background behind them. The background should only be as wide as the text itself, which works fine if both the title and subtitle are short enough, but starts breaking down if the subtitle is longer than one line.



.entry-title-wrap {
display: flex;
flex-direction: column;
align-items: center;
background-color: rgba(255,255,255,0.7);
padding: 6px 12px;
margin: auto;
border-radius: 2px;
h1 { font-size: 48px; }
h2 { font-size: 32px; }
}

<header class="entry-header">
<div class="entry-title-wrap">
<h1 class="entry-title">Nick Dourado</h1>
<h2 class="entry-subtitle">If the title is longer than one line so that it breaks over the line it makes the whole box way too big.</h2>
</div>
</header>





As soon as the subtitle is longer than the screen width and breaks onto more than one line, the h2 tag containing it expands to the full width of the container, which pushes the white background out to the edges as well. It also aligns the text to the left of the h2 unless I add
text-align: center;
event though it should be centered because of the flexbox styling.

How can I keep the white box constrained to the width of the text, and stop the h2 from expanding to the container width? If possible I would also love to force the subtitle to break in the middle of the text rather than one word at a time, so that all the lines are more or less the same length.

Here it is in CodePen. You can see how it should look if you make the subtitle sentence shorter.

This is the old version of the website it's for: http://theartsabstract.ca/post/151891941177/nick-dourado-on-halifaxs-improvised-music-scene

Answer

Aligning block elements in center with flex is not the same as using text-align center on headings. So go ahead and add the text-align:center on them.

I also made a few other changes.

  • removed image underlay
  • set image as background instead, and set size to "cover"
  • added some padding so your white box doesn't hit edge

As far as the text wrapping at middle, I'm not sure of any way to do that besides setting a media query for when the text starts to wrap, and then updating the heading with a max-width in CSS. See CodePen below

http://codepen.io/anon/pen/kkdgjX?editors=1100

Comments