CSS add small border bottom to text using selector ::after

16,918

Solution 1

h3
{
  border-bottom: 3px solid #000;
}

h4::after
{
  content: '';
  border-bottom: 3px solid #000;
  width: 10px;
  display: block;
}

adding a display: block; on your pseudo element will do the trick.

Solution 2

h3
{
  border-bottom: 3px solid #000;
}
h4{
display : inline-block;
}
h4::after
{
    content: '';
    border-bottom: 8px solid #000;
    width: 52px;
    display: block;
    margin: 0 auto;
}
<h3>
  Hello, this border is too long
</h3>

<h4>
  Hello, this border should be small
</h4>

Share:
16,918

Related videos on Youtube

Linesofcode
Author by

Linesofcode

Updated on June 04, 2022

Comments

  • Linesofcode
    Linesofcode almost 2 years

    I need to add a small border bottom to my text using the selector ::after.

    <h3>
      Hello, this border is too long
    </h3>
    
    <h4>
      Hello, this border should be small
    </h4>
    

    The <h3> element has a normal border, which fills the entire space of the text. But I need the <h4> element to only have a border with 10px length.

    Basically this is what I'm trying to achieve:

    enter image description here

    So I tried to play a little with CSS without success:

    h3
    {
      border-bottom: 3px solid #000;
    }
    
    h4::after
    {
      content: '';
      border-bottom: 3px solid #000;
      width: 10px;
    }
    

    https://jsfiddle.net/qkw37scn/2/

  • Jean-François Beauchamp
    Jean-François Beauchamp over 5 years
    The above answer will work to show the pseudo-element border, but it won't be sufficient to make it centered as shown in the OP example.