'How to change the length/position of text-decoration:underline?
I would like to have some words underlined where the underline can be a different length. I would also like to be able to change the position of the underline (move it further left or right under the word). It seemed to be a pretty easy task, but I can't get it to work.
.underline {
border-bottom: 1px solid #5fca66;
padding-bottom: 5px;
}
This is a <span class="underline">sentence</span>. I would like some words to have longer <span class="underline">underlines</span> than others. I would also like to be able to change the <span class="underline">position</span> of the <span class="underline">underline</span>(to be centered under the word, for example).
Solution 1:[1]
Use gradient and you can easily adjust size and position:
.underline {
background-image: linear-gradient(#5fca66 0 0);
background-position: bottom center; /*Adjust the background-position to move the line*/
background-size: 80% 2px; /*Adjust the background size to control length and height*/
background-repeat: no-repeat;
padding-bottom: 4px; /* this can also control the position */
}
.small {
background-size: 50% 1px;
}
.left {
background-position: bottom left;
}
.center-close {
background-position: bottom 5px center;
background-image: linear-gradient(red 0 0);
}
.right {
background-position: bottom right;
}
.close {
padding-bottom: 0;
background-position: bottom 5px center;
background-image: linear-gradient(blue 0 0);
}
.big {
background-size: 100% 3px;
}
.far {
padding-bottom: 10px;
background-image: linear-gradient(purple 0 0);
}
body {
font-size: 30px;
}
This is a <span class="underline">sentence</span>. I would like <span class="underline close">some words to have</span> longer <span class="underline left">underlines</span> than others. I would <span class="underline big center-close">also like</span> to be able to change the <span class="underline small right">position</span> of the <span class="underline big">underline</span>(to
<span class="underline far">be centered under the word, for example</span>).
Solution 2:[2]
this can be done using pseudo element.
.underline {
position:relative;
}
.underline:after{
content: "";
position:absolute;
bottom:-2px;/*position the underline using left and bottom property*/
left:0;
width:50px;/* adjust the width of underline as you like*/
border-bottom:1px solid #ccc;/* adjust the underline width and color as you like*/
}
<p>This is <span class='underline'>sample</span> text</p>
Solution 3:[3]
.underline {
position: relative;
}
.underline:before {
content: '';
position: absolute;
display: block;
/* you can adjust the properties to your liking */
bottom: 0;
left: 0;
width: 100%;
border-bottom: 1px solid #5fca66;
}
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 | Kaleem Nalband |
Solution 3 |