Font-Weight CSS Transition in Chrome

前端 未结 7 2066
生来不讨喜
生来不讨喜 2020-12-06 04:28

Trying to get font-weight to gracefully transition from \'400\' to \'600\' using CSS but it doesn\'t appear to be working in Chrome. Is this a known bug or am

7条回答
  •  独厮守ぢ
    2020-12-06 05:02

    Although there is no direct way to get the font-weight to smoothly transition, I have found a way to do this indirectly (although with some limitations).

    In essence you can simply use one of the pseudo elements in order to make a mirror copy of the element whom font you want to transition to bold, where the font-weight on the pseudo element is bold and the opacity is 0. And on hover simply transition the pseudo element's opacity and that does the trick with a very smooth transition.

    You can see a demo here:
    http://jsfiddle.net/r4gDh/45/

    HTML:

    text will turn to bold on hover

    In the HTML you can already see one of the limitations, because we are using pseudo elements we need to pass the contents of the element as an attribute as well, so the content is duplicated.

    CSS:

    .element,
    .element::before {
        background: red;
        font-weight:normal;
        font-size:40px;
    
        text-align:center;
    
        display: inline-block;
    
        padding: 0px 30px 0px 30px;
    
        position: relative;
        top: 0;
        left: 0;
    }
    .element::before {
        position: absolute;
        top: 0;
        left: 0;
    
        width: 100%;
        height: 100%;
    
        padding: 0;
    
        content: attr(data-text);
        opacity: 0;
    
        font-weight: bold;
    
        transition: all 1s linear;
    }
    .element:hover::before {
        opacity: 1;
    }
    

    The second limitation comes from the nature of the technique, namely because you are simply overlaying the pseudo element over the original, then the element needs to have a solid background or this will not work, because the original element will remain visible in the background.

    One thing you should really keep an eye on is that the pseudo element and the original element have the same dimensions, to this end, in the demo, I've removed the padding on the pseudo element, so you may need to do something similar.

    As you can see, this way of getting the font-weight transition is not without it's problems and far from ideal, but this is the best I can currently think of and in limited cases like for buttons and what not this is quite useful and if done correctly will look decent even in legacy browsers.

提交回复
热议问题