Search code examples
htmlcsstwitter-bootstrapbordercentering

Resize bottom border on a heading element to fit the text width and also be responsive


I want to make the bottom border narrower and responsive while keeping text centered at the same time. How could I achieve that? I tried using width property explicitly but that is apparently not working.

DEMO: https://www.bootply.com/jEB0e4Ao61

h1 {
  border-bottom: 1px solid orange;
  padding-bottom: 5px;
  width: 400px;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container text-center features">
  <h1>Features</h1><br>
</div>


Solution

  • You need to do 2 things:

    1. use display:inline-block;
    2. set width: auto

    Change from a block element so the border will resize to the width of the text:

    <h1> is a block element, which will automatically stretch to 100% width of the container. setting width to auto or a percentage will apply to the default width, i.e. 50% will be 50% of the container width.

    Using inline-block and width of auto will make the heading only as wide as the heading itself, which means you won't need media queries for different screen sizes. This will make the border the exact width of the heading itself.

    To make the "underline" extend wider than the text width:

    If you would like extra space at the sides of the heading, you can use padding to do this. For example:

    padding-left:20px; padding-right:20px;
    

    will add 20px to either side of the heading, extending the element width which will also extend the bottom border by 20px on both sides.

    Working demo:

    h1 {
      border-bottom: 1px solid orange;
      display: inline-block;
      width: auto;
      text-align: center;
      margin: auto;
      padding: 0 20px 5px; /* this adds 20px to the sides, extending the border  */
    }
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <div class="container text-center features">
      <h1>Features</h1><br>
    </div>
    <p>The "underline" for this heading extends 20px either side of the text by setting the left and width padding to 20px</p>