Utilizing Linear Gradients for Background:
Alternatively, you can achieve this effect using background images with the linear-gradient
property. One of the benefits of using a gradient is that it eliminates the need for extra pseudo-elements, allowing them to be utilized for other purposes. The thickness of the border is determined by the background-size
in the Y-axis, while the width of the border is based on the size in the X-axis. To center the border, the background-position
property is employed.
However, one downside is the limited browser support for linear-gradient
compared to pseudo elements. Gradients are only compatible with IE10 and above.
h1 {
display: inline-block;
padding-bottom: 4px; /* creating space between text and border */
background: linear-gradient(to right, black, black);
background-repeat: no-repeat;
background-size: 20px 2px;
background-position: 50% 100%;
}
<h1>This text can exceed the border length</h1><br>
<h1>Some shorter text</h1><br>
<h1>Some text</h1>
Using a Pseudo-element:
Another approach is to utilize a pseudo-element to create the desired effect. By adding a pseudo-element with a 20px width
and positioning it absolutely, we can achieve the same visual outcome. The left: 50%
, translateX(-50%)
properties are used to position the pseudo-element at the center. The thickness of the border is dictated by the height
of the pseudo-element, while the color is determined by the background
property.
An advantage of this method is its broader browser compatibility, as it should function properly in IE8 and newer versions.
h1 {
position: relative;
display: inline-block;
padding-bottom: 4px; /* creating space between text and border */
}
h1:after {
position: absolute;
content: '';
left: 50%;
bottom: -2px;
width: 20px;
height: 2px;
background: black;
transform: translateX(-50%);
}
<h1>This text can exceed the border length</h1>
<br>
<h1>Some shorter text</h1>
<br>
<h1>Some text</h1>