Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS decrease space between text and border

When hovering a link I want it to get an underline. The underline should be 2px strong and 4px below the text.

With

text-decoration: underline

I get a 1px strong line which is 4px below. (Distances vary by font)

If I write

border-bottom: 2px solid #000;

I get a 2px line which is about 10px below the text.

How can I decrease the distance between the text and the border?

padding-bottom: -6px

does not work. Any negative value with padding-bottom does not work.

Or how can i get the underline to be 2px strong?

http://jsfiddle.net/qJE2w/1/

Update 2022: For everyone coming here years after this question was asked:

It's now possible to change the underline via CSS. There are "new" properties like text-underline-offset and text-decoration-thickness.

like image 687
obs Avatar asked Feb 06 '13 15:02

obs


People also ask

How do I reduce the space between border and text in HTML?

Make your H1 as display:inline-block so that vertical align will have its effects on it. And apply margin:0 auto that should make the text horizontally centered. So your text will be finally center aligned in the page (vertical & horizontal) with the border around it.

How do I remove border spacing in CSS?

This is a Default behavior of the table cells that there is some space between their Borders. To remove this space we can use the CSS border-collapsing Property. This Property is used to set the borders of the cell present inside the table and tells whether these cells will share a common border or not.


3 Answers

One quick solution that comes into my mind is to apply the border on a pseudo-element:

.border{
    position: relative;
}

.border:hover::after{
    content:'';
    position:absolute;
    width: 100%;
    height: 0;    
    left:0;
    bottom: 4px;                    /* <- distance */
    border-bottom: 2px solid #000;  
}

(example)

like image 98
nice ass Avatar answered Oct 17 '22 15:10

nice ass


You can use line-height for decrease distance.

.underline {
  display: inline-block;
  line-height: 0.9; // the distance
  border-bottom: 1px solid;
}

Drawback of this method -- because we use block display it works only for single line of the text.

like image 43
vatavale Avatar answered Oct 17 '22 13:10

vatavale


You can use background with linear-gradient to produce a border, and with it you can position it anywhere.

For example:

background-image: linear-gradient(currentColor, currentColor);
background-position: 0 95%; /* determines how far from bottom */
background-repeat: no-repeat;
background-size: 100% 5px; /* second value determines height of border */

http://jsfiddle.net/1mg4tkwx/

Credit: https://www.dannyguo.com/blog/animated-multiline-link-underlines-with-css/

like image 3
Estevão Lucas Avatar answered Oct 17 '22 15:10

Estevão Lucas