Adding Lines Before & After an Element without JavaScript

Ever seen a title with lined before and after to style it? I needed to have lines around my titles for a website I was building, but I wanted them to dynamically resize around the title. Here is an example of what I mean:

Title


There are tons of ways to do this, but unfortunately, most of these do not work with any size title or use JavaScript. I avoid JS like the plage, and always prefer to go with CSS only solutions, so those were not an option. I’ve also seen people use a white background to cover part of a straight line, but that is not always possible when you have images, gradients, or similar in the background. Almost every solution I saw either did not work for all occasions, or required JS. After messing around with it, here is the CSS only solution I used.

Here is the HTML:

<div id="title">Title</div>


Here is the CSS:

#title { overflow: hidden; padding: 10px 26px 0; }
#title:after, #title:before {
    content: '';
    display: inline-block;
    height: 1px;
    width: 100%;
    margin: 0;
    background: #999;
    text-indent: 20px;
    position: relative;
    vertical-align: middle;
}
#title:after {
    left: .5em;
    margin-right: -100%;
}
#title:before {
    right: .5em;
    margin-left: -100%;
}

The final result looks like this:

Title

Leave a comment

Your email address will not be published. Required fields are marked *