text-decoration: underline vs border-bottom

后端 未结 7 1815
后悔当初
后悔当初 2021-02-13 04:04

What is the difference to use {text-decoration: underline} and {border-bottom: ...}?

which is easy to style and cross browser compatible?

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 04:29

    While there are always going to be cases where one is more appropriate than the other, border-bottom offers much more precise control over text-decoration and is therefore probably the preferred method. Here's a quick (likely not exhaustive) list of properties that border-bottom can control/enable that text-decoration cannot:

    1. Spacing between text and "underline"
    2. "Underline" style (dotted, dashed, solid, gradient, image)
    3. Thickness
    4. CSS transitions/animations
    5. Separation of color between text and "underline"

    In many cases, most of these abilities will not be needed - but it is good to have them available! I've switched to using border-bottom primarily for the ability to put a few pixels of padding between the text and the underline; the next most common use I've found is divorcing the underline color from the text color.

    With CSS variables now shipping in every major browser, a "reset" stylesheet might look something like this:

    :root {
        --link-color: blue;
        --hover-color: purple;
        --underline-color: var(--link-color);
    }
    
    a {
        color: var(--link-color);
        text-decoration: none;
        border-bottom: 1px solid var(--underline-color);
    }
    
    a:hover {
        color: var(--hover-color);
        border-bottom-color: var(--hover-color);
    }
    

    This way, links will display as expected on a "default" basis, yet still allow for customization as needed.

提交回复
热议问题