guy mograbi
guy mograbi

Reputation: 28728

bold font makes width change

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

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

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

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

span {
  padding: 20px;
}

div:hover {
  font-weight: bold;
}
<div><span>This is my div</span></div>

How can I resolve this problem?

EDIT:

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

Upvotes: 2

Views: 8362

Answers (4)

adinas
adinas

Reputation: 4550

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/

Upvotes: 1

TheZver
TheZver

Reputation: 1582

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;
}

Upvotes: 1

Quentin
Quentin

Reputation: 944442

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.

Upvotes: 13

Phil
Phil

Reputation: 473

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

Upvotes: 0

Related Questions