Home > Mobile >  CSS Flexbox: Gettings headings with background colors to fit the text
CSS Flexbox: Gettings headings with background colors to fit the text

Time:11-01

I'm trying to get and h1 and h2 to have background colors around the text. Because it's Flexbox, the background colors fill the entire row, not just the text.

I added display: inline; to each heading. Now the background colors fit the text, but because the display is no longer flex, the text is next to one another instead of the H2 being underneath.

Not sure what to do here. The actual page is here: https://www.ihfanh.com/

Here's a simplified version of the HTML and CSS.

<section>
  <div>
    <h1>This is a heading one</h1>
    <h2>This is a heading 2</h2>
  </div>
</section>

CSS

section { display: flex; flex-direction: column; }
div { -webkit-flex: 1; flex: 1; }
h1, h2 { display: inline; }
h1 { background: #F00; color: #FFF; font-size: 60px; padding: 8px 24px; }
h2 { background: #554c55; color: #FFF; font-size: 30px; margin-top: 16px; padding: 8px 24px; }

CodePudding user response:

Add width: fit-content; instead of display: inline

section { display: flex; flex-direction: column; }
div { -webkit-flex: 1; flex: 1; }
h1, h2 { width: fit-content;}
h1 { background: #F00; color: #FFF; font-size: 60px; padding: 8px 24px; }
h2 { background: #554c55; color: #FFF; font-size: 30px; margin-top: 16px; padding: 8px 24px; }
<section>
  <div>
    <h1>This is a heading one</h1>
    <h2>This is a heading 2</h2>
  </div>
</section>

  • Related