There are 2 key steps you should take:
- Utilize
display:inline-block
;
- Specify
width: auto
Transition from a block element to allow the border to adjust according to text width:
A <h1>
is classified as a block
element, automatically occupying 100% of container width. When setting width to auto or a percentage, it will apply based on default width, such as 50% representing half container width.
By using inline-block
and specifying width as auto
, the header's width matches its content only, eliminating the requirement for media queries for various screen sizes. Consequently, the border aligns precisely with the header width itself.
To extend the "underline" beyond text width:
If a wider space surrounding the heading is preferred, padding can be utilized. For example:
padding-left:20px; padding-right:20px;
Adds 20px on each side of the header, increasing element width which subsequently extends bottom border by an additional 20px on both sides.
See a functional demonstration below:
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 defining left and width padding as 20px</p>