Search code examples
htmlcsspseudo-element

Make my h2 border bottom just underline the text not the div


I want to make the border-bottom style of h2:after to fill the text width, not the entire div element.

Here's my code:

.text_box{
   margin: 0 auto;
   width: 355px;
   background:red;
}

h2{
   margin: 0 auto;
   font-weight: 100;
   font-size: 1em;
   text-align: center;
   padding:20px;
}

h2:after{
   content:'';
   background:black;
   width:100%;
   height:2px;
   display:block;
}
<html>
  <head>
  <title></title>
  </head>
<body>
<div class="text_box">
    <h2>NEWS & ACCOLADES</h2>
</div>
</body>
</html>

Codepen: http://codepen.io/rezasan/pen/YNZQEQ


Solution

  • Here is the solution of your question.
    

    .text_box {
        margin: 0 auto;
        width: 355px;
        background: red;
        text-align: center;
    }
    h2 {
        margin: auto;
        font-weight: 100;
        font-size: 1em;
        text-align: center;
        padding: 20px;
        position: relative;
        display: inline-block;
    }
    h2:after {
        content: '';
        background: black;
        width: 100%;
        height: 2px;
        display: block;
     
    }
    <div class="text_box">
            <h2>NEWS & ACCOLADES</h2>
    </div>