Search code examples
htmlcsspseudo-class

heading with horizontal line on either side


I am working on some CSS where the design calls for page titles (headings) to be centered with horizontal lines that are vertically centered on either side. Further, there is a background image on the page so the background of the title needs to be transparent.

I have centered the title and I can use pseudo class to create the line. But I need the line disappear when it cross the text of the title.

I considered using a background gradient that goes transparent where the words are, but since each title could be a different length, I wouldn't know where to put the stops.

Here is the CSS so far:

h1 {  
    text-align: center;  
    position: relative;  
    font-size: 30px;  
    z-index: 1;  
}  

h1:after {  
    content: '';  
    background-color: red;  
    height: 1px;  
    display: block;  
    position: absolute;  
    top: 18px;  
    left: 0;  
    width: 100%;  
}  

Here is where I'm at: http://jsfiddle.net/XWVxk/1/

Can this be done with CSS without adding any extra HTML?


Solution

  • Look at this http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition , here is your answer.

    Here is your original code modified

    h1 {
        position: relative;
        font-size: 30px;
        z-index: 1;
        overflow: hidden;
        text-align: center;
    }
    h1:before, h1:after {
        position: absolute;
        top: 51%;
        overflow: hidden;
        width: 50%;
        height: 1px;
        content: '\a0';
        background-color: red;
    }
    h1:before {
        margin-left: -50%;
        text-align: right;
    }
    .color {
        background-color: #ccc;
    }
    <h1>This is my Title</h1>
    <h1>Another Similar Title</h1>
    <div class="color"><h1>Just Title</h1></div>

    Note: the article is not online anymore, here is the last good archived version: http://web.archive.org/web/20140213165403/http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition