'How to shorten the length of underline by reducing 30px from both ends in HTML?
I want to add an underline under my h1 heading and make it just a little short then the heading itself. 30px space should remove from both ends. how to fix this?
<h1>Heading</h1>
h1 {
border-bottom: 2px solid #000000;
width: fit-content;
}
Solution 1:[1]
h1 {
position: relative;
display: inline-block;
}
h1:after {
content: "";
width: calc(100% - 60px);
height: 100%;
position: absolute;
left: 30px;
border-bottom: 2px solid black;
}
<h1>Heading</h1>
One way to do it is with ::after element. Use left to shift it for 30px.
Solution 2:[2]
It depends a bit on what you want to do if the heading is long and overflows to another (shorter) line, but assuming you literally want just a border shortened by 60px then you can add a before pseudo element of the same height but less width.
h1 {
width: fit-content;
position: relative;
--indent: 30px;
}
h1::before {
width: calc(100% - (2 * var(--indent)));
height: 100%;
content: '';
position: absolute;
top: 0;
left: var(--indent);
;
border-bottom: 2px solid #000000;
}
<h1>Heading</h1>
This snippet defines a variable with the indent required (30px) so it will be easy for you to change it if required.
Solution 3:[3]
You may fake the underline via a background and shorten it via background-size:
here is an example of the idea:
h1 {
background: linear-gradient(to top, #000000 0 2px, transparent 2px) 50% 0 / calc(100% - 60px) 100% no-repeat;
width: fit-content;
}
h2 {
color: green;
margin: auto;
background: linear-gradient(to top, currentColor 0 2px, transparent 2px) 50% 0 / calc(100% - 60px) 100% no-repeat;
width: fit-content;
}
h2+h2 {
color: tomato;
line-height: 0.95em;
transition:0.25s
}
h2 + h2:hover {line-height:1.6em;}
<h1>Heading</h1>
<p>extras for infos</p>
<h2>Match colors via currentColor</h2>
<h2>move that fake underline closer or further away</h2>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | A Haworth |
| Solution 3 |
