A title in a separator line

Like for the legend tag in a fieldset, we insert a text on a separation bar and the background behind the text is erased.

This allows to separate sections in one page, while minimizing the use of space.

Compatibility: IE6 +, Chrome, Firefox, Safari.

The idea is to put a layer with the text inside another, give a dark background to the container and reduce its height to display a line, give a white background to the internal layer and shift it to make it appear inside the container.

Demonstration:

Hello World!

HTML code :

<div class="bartext"><div>Hello World!</div></div>

CSS code :

.bartext {
height:8px;
width:100%;
padding:0px;
background:#333;
overflow:visible;
position:relative;
margin-top:24px;
}
.bartext div {
color:#333;
background-color:#FFFFFF;
top:-5px;
margin-left:100px;
padding: 0 8px 8px 8px;
display:inline;
position:absolute;
}

It is possible to change the color of the bar and the text, the thickness of the bar with the height property, the position of the text is given by the margin-left property.
If you want to center the text, use text-align: center in the rule bartext and remove margin-left in bartext div...

Rounding the ends of the bar

Just add a border-radius property in the rule .bartext.

border-radius:8px;

Here is the result:

Hello World!

Or give it a slanted end

The example below is in pure CSS:

Hello World!

This effect is difficult to produce in pure CSS, and we should add a tag for it.

<div class="slantdiv"></div>
<div class="barslant"><div>Hello World!</div> <br>

Here is the CSS code :

.barslant {
padding:0px;
overflow:visible;
position:relative;
background:#333;
height:0;
line-height:16px;
margin-top:0;
width:90%;
}
.barslant div {
background-color:#FFFFFF;
margin-left:100px;
padding:0 8px 8px 8px;
display:inline;
position:absolute;
color:#000;
top:-12px;
}
.slantdiv {
width:96%;
height:0px;
border-bottom:8px solid #333;
border-right:8px solid white;
margin-top:24px;
}

A limitation in the method used - whatever the shape of the bar - it is important that the background of the page is white, or more precisely that the background of the text is the same color as that of the page.

If you want to use this widget on a page whose background is an image, another solution is presented on jsfiddle. It also has the advantage that a single tag is required in the HTML code. But it also has its drawbacks. Position the text on the left or right side is almost impossible. Customizing the bar as we did above is not feasible. Compatibility is also restricted to IE from version 8.

The CSS FAQ will give you more tips and on the homepage you have others tips to create graphic effects without images.

License : You are free to use this code for the presentation of your pages, without restriction. Do not reuse the content of this page or the code as the subject of other online tutorials. This license applies to all content of the site.