Search code examples
htmlcssmarkup

How do I draw an Ideal line between two headers?


My HTML code has this structure:

h1 {
  text-align: center;
  font-size: 20pt;
  padding-bottom: 0;
}

h2 {
  text-align: center;
  font-size: 16pt;
}

<body>
  ...
  <div id="container">
    <h1>Title</h1>
    <h2>Sub</h2>
  </div>
  ...
</body>

I want to "draw" a line between those two headings like this:

title - sub

It should adjust to the width of the headings:

longer title - sub

title - longer subtitle

(Excuse my image editing skills)

Is there a simple css-only way to do so?


Solution

  • You can handle this problem with a simply pseudo element. No html structure changing or non-support css of cross browers. We need to use table display on the parent and make a new element (your border with pseudo) on the <h1>.

    Look at this example:

    #container {
      display: table;
      margin: 0 auto;
      text-align: center;
    }
    
    h1:after {
      content:"";
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      border-bottom: 3px solid red;
    }
    
    h1, h2 {
      margin: 5px 0;
      padding: 0 10px 5px;
    }
    
    h1 {
      position: relative;
      font-size: 20pt;
    }
    
    h2 {
      font-size: 16pt;
    }
      <div id="container">
        <h1>long long title</h1>
        <h2>Sub</h2>
      </div>
    
      <div id="container">
        <h1>h1</h1>
        <h2>Sub</h2>
      </div>
    
    
     <div id="container">
        <h1>h1</h1>
        <h2>long long subtitle</h2>
      </div>

    Fiddle demo