Search code examples
htmlcssbackground-imagebackground-repeat

CSS Background : Adding left padding via using repeat-x with single element


I try to create heading like this...

Title --------------------

This line with a custom image background

HTML :

<h2>Title</h2>

CSS :

h2 {background:url('line.png') repeat-x 15px 10px;}

Result :

enter image description here

Live : http://jsfiddle.net/5G2aq/


I try to repeat this image with X-axis and add some padding into the left.

But it doesnt work, 15px doenst work... or what ?

PS :Try to do with a single element <h2>, not :after or full-long image

Any trick ?


Solution

  • Do it like this, use :after pseudo with content: ""; and be sure you use display: block;, now we use position: absolute; and assign position: relative; to the container element. Last but not the least we use overflow: hidden; so that we don't get dirty scroll.

    Demo

    h2 {
        position: relative;
        overflow: hidden;
    }
    
    h2:after {
        position: absolute;
        height: 2px;
        content: "";
        display: block;
        width: 100%;
        top: 50%;
        left: 60px;
        background:url(http://oi39.tinypic.com/m7t8xw.jpg) repeat-x;
    }
    

    Coming to your solution, you are using repeat-x, so you won't see the background-position changing on the x axis as the image is repeating, if you want to go for this approach, you shouldn't repeat.


    Even better approach

    Demo 2 OR Demo 3 (Using your image)

    <div><span>Hello</span></div>
    
    div {
        border-top: 1px solid #000;
        margin: 20px;
        position: relative;
    }
    
    div span {
        display: block;
        position: absolute;
        top: -12px;
        background: #fff;
        padding-right: 10px;
    }
    

    The above way will be title width independent, I would've chosen this way

    Note: You can replace div with h2