0

Kind of a convoluted title, but easy enough to demonstrate

#txt {
  padding: 5px;
}
#txt:hover {
  font-weight: bold;
}
#test {
  display: inline-block;
  border: solid 1px black;
  min-width: 100px;
}
<div id="test">
  <div id="txt">This is some text</div>
</div>

So I have the above situation.

Is there anything I can do with CSS that will avoid the container (test) from resizing when I hover over the text? Like take up the padding or margin for the resize. Or set the width so that it is enough to handle the bolded text (but still be dynamic).

Dan
  • 10,614
  • 5
  • 24
  • 35
  • Possible duplicate of [Inline elements shifting when made bold on hover](http://stackoverflow.com/questions/556153/inline-elements-shifting-when-made-bold-on-hover) – JP. Aulet Mar 31 '16 at 23:28
  • Setting a min-width that would accommodate either font-weight bold or normal is much less brittle than fiddling with margins. You can adjust margin-left and margin-right on hover to adjust for the larger text size for the bolded state, but it's brittle - change font and your calculations are off and your container will jitter on hover (or if your user zooms...). – dogwoodtree-dot-net Apr 01 '16 at 01:12

1 Answers1

13

Here is an idea, use the before and after attributes to size the element based on the bold text width. Unfortunately, this requires a change to your markup.

#txt {
  line-height: 1.4em;
  padding: 5px;
  text-align: center;
}
#txt::before {
  content: attr(data-content);
  display: block;
  font-weight: bold;
  height: 0px;
  visibility: hidden;
}
#txt::after {
  content: attr(data-content);
  font-weight: normal;
}
#txt:hover::after {
  font-weight: bold;
}
#test {
  display: inline-block;
  border: solid 1px black;
  min-width: 100px;
}
<div id="test">
  <div id="txt" data-content="This is some text"></div>
</div>

Alternately, use text-shadow to bold your text.

#txt {
  padding: 5px;
}
#txt:hover {
  text-shadow: 0.5px 0px 0px #555, -0.5px 0px 0px #555;
}
#test {
  display: inline-block;
  border: solid 1px black;
  min-width: 100px;
}
<div id="test">
  <div id="txt">This is some text</div>
</div>
user2867288
  • 1,979
  • 16
  • 20