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).

2
  • Possible duplicate of Inline elements shifting when made bold on hover
    – JP. Aulet
    Mar 31, 2016 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...). Apr 1, 2016 at 1:12

1 Answer 1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.