Home > database >  Small top border for header while maintaining header's height
Small top border for header while maintaining header's height

Time:02-25

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>

CodePudding user response:

  • 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>

  •  Tags:  
  • css
  • Related