Search code examples
cssclasshtmlunderline

How can I create a line after my text to the width of the container?


Yes, I'm a newb so please go easy. I know there's got to be several ways to accomplish this. Basically I've been trying to come up with a consistent way to have a header with a line after the text that will run to the full width of a container element.

Something like this:

This is my header _______________________________________________________ |<- end container
This is another header __________________________________________________ |<- end container

I'm trying to create a .line class that will use bottom-border to create the line but I've been unsuccessful at creating a variable length line that will extend the full width of the container.

Here's what I've tried:

CSS:

.line
{
    display:inline-block;
    border-bottom:2px #5B3400 solid;
    margin-left:5px;
    width:80%;
}

HTML:

    <h2>Our Mission<span class="line"></span></h2>

Of course this only gives me a line 80% of the container from the left border including the width of the text. How can I create a line that begins after the text and runs the full width of the border regardless of how much text is on the same line?

I know this should be easy but I haven't been able to find a solution yet.

Thanks!


Solution

  • THIS METHOD WILL WORK WITH TEXTURED BACKGROUNDS (background images):

    You can try using this method instead, if your <h2> is on top of a background image.

    HTML:

    <h2 class="line-title"><span>This is my title</span><hr /></h2>
    

    CSS:

    .line-title {
        font-size: 20px;
        margin-bottom: 10px;
        padding-top: 1px; /* Allows for hr margin to start at top of h2 */
    }
    
    /* clearfix for floats */
    .line-title:after {
        content: "";
        display: table;
        clear: both;
    }
    
    .line-title span {
        padding-right: 10px;
        float: left;
    }
    
    .line-title hr {
        border:1px solid #DDD;
        border-width: 1px 0 0 0;
        margin-top: 11px;
    }
    

    See the working example here: http://jsfiddle.net/yYBDD/1/

    How it Works:

    1. the <h2> tag acts as a container for a floated element.

    2. the <span> is floated left, causing the <hr /> to collapse to the left and fill the right space.

    3. the <hr /> acts as the line, and fills up the remaining space to the right.