Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I draw an Ideal line between two headers?

Tags:

html

css

markup

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?

like image 994
Scriptim Avatar asked Dec 04 '16 14:12

Scriptim


1 Answers

The easiest and most flexible way i think is to use Flexbox. Just add some left and right padding to h1 and h2 elements so line can always be a bit longer then text.

body {
  text-align: center;
}
.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
h1 {
  font-size: 20px;
  padding: 0 10px;
}
h2 {
  font-size: 16px;
  padding: 0 10px;
}
.line {
  height: 3px;
  width: 100%;
  background: red;
}
<div class="container">
  <h1>Lorem ispum</h1>
  <span class="line"></span>
  <h2>Sub</h2>
</div>
<hr>
<div class="container">
  <h1>Ispum</h1>
  <span class="line"></span>
  <h2>Lorem ipsum dolor sit amet.</h2>
</div>

Update: You can actually do this with pseudo-element on .container but you need to specify order so that line shows after h1 element.

body {
  text-align: center;
}
.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
.container > h1 {
  order: 1;
  font-size: 20px;
  padding: 0 10px;
}
.container > h2 {
  padding: 0 10px;
  order: 3;
}
.container:before {
  content: '';
  height: 3px;
  width: 100%;
  background: red;
  order: 2;
}
<div class="container">
  <h1>Lorem ispum</h1>
  <h2>Sub</h2>
</div>
<hr>
<div class="container">
  <h1>Ispum</h1>
  <h2>Lorem ipsum dolor sit amet.</h2>
</div>
like image 164
Nenad Vracar Avatar answered Sep 24 '22 13:09

Nenad Vracar