Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centered text with hr-like line on both sides, without using a table

I need to create a headline with equal length lines on both sides of the headline text, and a fixed size padding between the lines and the text. The text will vary so it must not set a width. The lines should take up all remaining width available in the headline container. The headline text must not set a background because the background behind it will vary. Something like this:

--------------------------------------------------------- Some text ---------------------------------------------------------

I solved it using a table:

<table width="100%">
  <td><hr /></td>
  <td style="width:1px; padding: 0 10px; white-space: nowrap;">Some text</td>
  <td><hr /></td>
</table>​

You can try it out here: http://jsfiddle.net/md2dF/3/

Semantically this is a really bad solution, the headline has nothing to do with tabular data. How would you do this without a table?

To summarize (because the suggested solutions have all overlooked one or more requirements):

  • The headline must not have a fixed width
  • The headline text must not have a background
  • The headline text must not have a fixed width
  • The lines on either side of the text must take up all remaining width
  • The padding between the lines and the text must have a fixed width
  • If in doubt, look at http://jsfiddle.net/md2dF/3/
like image 527
Robert Kajic Avatar asked Sep 20 '12 23:09

Robert Kajic


1 Answers

Newer answer that works on newer versions of IE and Firefox

Without any tricks: ​

fieldset.title {
    border-top: 1px solid #aaa;
    border-bottom: none;
    border-left: none;
    border-right: none;
    display: block;
    text-align: center;
}

fieldset.title legend {
    padding: 5px 10px;
}
<fieldset class="title">
    <legend>Some text</legend>
</fieldset>

Live demo on jsfiddle

like image 198
Gerald Schneider Avatar answered Sep 28 '22 12:09

Gerald Schneider