Search code examples
htmlcssresizespacingdynamic-resizing

Customizing variable display widths of :before and :after sections


I am implementing a custom theme into a SaaS ecommerce website, and I want to create a custom title bar with decorative graphics to either side of the text, inside an h2 tag. Because the platform is only partially open-source, and I want to apply this styling globally, it's not feasible to add HTML markup, so I'm looking for a graceful way to do this using CSS only.

Typically, I would apply title bar decor using simple :before and :after tags, with some positioning, so they would appear on either side of the h2 title text - regardless of how wide that text was on the screen. But in this particular design case, I need the side elements to "fill in" the remainder of the horizontal space to either side of the text, all the way to the edges, with the background image. I've tried a variety of things, such as setting the :before and :after elements to display:block and floating them (which only works if I give them a fixed or % width, which I can't really do), or setting them to table-cell (but since I can't separately wrap the text in the middle, this doesn't really calculate the width correctly, either). I KNOW there's got to be a way to do this. How would you handle it?

The front-end code is super simple:

<h2 class="pagetitle">Page Title Here</h2>

Here's a visual example of what I'm trying to create: title bar with side elements


Solution

  • Use flex:

    body {
      background: navy
    }
    
    h2 {
      display: flex;
      text-align: center;
      background: ivory
    }
    
    h2:before,
    h2:after {
      content: '~';
      flex: 1 0;
      text-align: left;
      background: violet
    }
    
    h2:before {
      text-align: right
    }
    <h2>Page Title Here</h2>