Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Small top border for header while maintaining header's height

I would like to have a small top border on my headers. I did this with ::before pseudo but the heading height is now messed up because of its absolute positioning. Any element after the heading ignores the heading height because of course the absolute element is removed from document flow.

Is there a better way to achieve this look and feel and maintain the heading height as well? Preferably without positioning?

h3 { position: absolute; }

h3:before {
  position: relative;
  margin-top: -5px;
  content:'';
  position: absolute;
  background-color: #C70021;
  width: 20%;
  height: 3px;
  top: 0;
  left:0;
}
<h3>My Heading</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis nunc malesuada, aliquam leo nec, auctor sem</p>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • To use position: absolute; on a child box, such as ::before or ::after, or any descendant element, the parent just needs position: relative; (instead of the default position: static;).
    • So you don’t need position: absolute; on the h3.
  • You also have redundant properties set in your h3::before rule, btw.
h3 {
  position: relative;
}

h3::before {
  margin-top: -5px;
  content: '';
  position: absolute;
  background-color: #C70021;
  width: 20px;
  height: 3px;
  top: 0;
  left:0;
}
<h3>My Heading</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis nunc malesuada, aliquam leo nec, auctor sem</p>

However, alternative approaches exist, for example this is simpler:

h3::first-letter {
  text-decoration: overline #C70021;
  text-decoration-thickness: 3px;
}
<h3>My Heading</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis nunc malesuada, aliquam leo nec, auctor sem</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading