Search code examples
csshtml-heading

Adding background to h1, only on apty space


I'm trying to achieve this kind of effect

Basic example

Basically, I want the background for my heading to span across the available space, but not under the text. The problem is that this needs to be dynamic as the text can be in multiple languages. I can't simply put another background in a separate span for the text, since the overall background used a pattern image, and it can't just randomly start and stop depending on the length of the text.

I hope i made myself clear enough!

EDIT: since the example was not clear enough, here is another one: enter image description here


Solution

  • If you want to support the maximum number of browsers, then you need to add some additional markup for this to work:

    http://tinker.io/b6848

    <h1><span>Header Text</span><span/></h1>
    
    body {
        background: url(http://placekitten.com/600/400);
    }
    
    h1 {
        display: table;
        width: 100%;
    }
    
    h1 span {
        display: table-cell;
        white-space: pre;
    }
    
    h1 span:last-child {
        background: black;
        width: 100%;
    }
    

    There is a way to do this without additional markup using Flexbox, but it currently only works in Chrome, Opera, IE10, Firefox builds with experimental Flexbox support turned on, and maybe Safari.