2

I have a div with some text inside and a border.

<div><span>This is my div</span></div>​

When I hover on that div, I want the font to be bold.

div{
    border: 1px solid black;
    display:inline-block;
    padding:20px;
}

span{ 
    padding:20px;

}

div:hover{
    font-weight:bold;
}

This makes my div a bit wider - which causes an annoying flicker.

Example on JSFiddle

How can I resolve this problem?

EDIT:

The div's width has to grow with content, but not with weight.

guy mograbi
  • 27,391
  • 16
  • 83
  • 122

4 Answers4

13

Your div is inline-block and doesn't have an explicit width, so it shrink-wraps the content. The font is a proportional font, so it gets thicker (and takes up more horizontal space) when it is made bold.

Either give the div a fixed width, set it to block, or use a monospace font.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 3
    It depends on the font whether bold typeface glyphs are wider than normal typeface glyphs, so using monospace font does not necessarily help. Being monospace means that glyphs have the same width within a typeface, not necessarily across typefaces of the font. Moreover, some monospace fonts (e.g., Lucida Console) have only one typeface, so bolding them either fails or (usually in web browsers) causes algorithmically bolded and therefore wider glyphs to be used. – Jukka K. Korpela Oct 23 '12 at 17:35
2

You can simulate the bold affect using Text Shadow. so you would have

div:hover { 
text-shadow: 0 0 1px black, 0 0 1px black;
} 

You can control the affect by changing the 1px to a higher or lower number. You will need to change the color of the shadow depending on your text color too. Check out a whole article about this solution here: https://www.sitepoint.com/quick-tip-fixing-font-weight-problem-hover-states/

adinas
  • 4,150
  • 3
  • 37
  • 47
  • 1
    This should be the accepted answer. It creates the bold effect without having to adjust any other elements. – Mac Feb 18 '22 at 14:50
1

I got pretty close by playing with letter-spacing :

http://jsfiddle.net/thezver/U56R6/1/

<div>Asdf</div>
<div>ab acRsery</div>
<div>abc f</div>
<div>aMdNhjkl</div>
<div>1</div>

css:

div{
    display:inline-block;
    font-family:'Open Sans';
    font-size: 16px;
    padding:5px 10px;
    border:1px solid gray;
    letter-spacing: 0.5px;
}

div:hover{
    font-weight:bold;
    letter-spacing:-0.1px;
}
TheZver
  • 1,502
  • 2
  • 14
  • 19
0

You could set your div with a fixed width and center align your text for neatness

div{
    border: 1px solid black;
    display:inline-block;
    padding:20px;
    width: 150px;
    text-align: center;
}

span{
    padding:20px;
}

div:hover{ 
    font-weight:bold; 
} 

Working Example From jsFiddle

Hope this helps

Phil
  • 463
  • 3
  • 9